With the angular and other frameworks it is used to display values or call javascript functions inside braces in the middle of html.example codes:
<div>{{exibeNome()}}</div>
How can I use this without these frameworks.
With the angular and other frameworks it is used to display values or call javascript functions inside braces in the middle of html.example codes:
<div>{{exibeNome()}}</div>
How can I use this without these frameworks.
These frameworks compile HTML and insert what's inside {{ }}
into HTML. This is done differently from framework to framework.
This can be quite complex and at the outset unnecessary re-invent. Examples of this are as you mentioned the Angular but also Pug, Ejs, JSX, etc.
If you have an object and a piece of HTML, the thing could be done in a very simplistic way:
var conteudo = {
nome: 'Maria',
idade: function() {
return new Date().getFullYear() - 1978;
}
}
function parser(html) {
var regex = /{{(.+?)}}/g;
return html.replace(/{{(.+?)}}/g, function(match, cmd) {
return eval('conteudo.' + cmd.trim());
});
}
var p = document.querySelector('p');
p.innerHTML = parser(p.innerHTML, conteudo);
<p>A {{ nome }} tem {{ idade() }} de idade.</p>
The ideas within this code are:
eval()
within the correct context, could be using a .bind()
but simplified here