Using keys to display javascript

1

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.

    
asked by anonymous 27.05.2017 / 17:46

1 answer

1

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:

  • find the commands to execute on the object / class with content
  • create a function that runs eval() within the correct context, could be using a .bind() but simplified here
  • replace values in HTML
27.05.2017 / 18:16