How does the HTML5 template element work?

14

Recently I've seen some news about a new HTML element called <template> specified by W3C and has already been implemented in most modern browsers.

Apparently it allows you to create custom tags, much like in XML:

<minha-tag>
    <!-- -->
</minha-tag>

But it's still not clear to me what exactly it brings benefits and how far this tagging lets you go.

So, what would be the advantages of using this new element? When and where is your use most advised?

    
asked by anonymous 18.06.2014 / 04:35

1 answer

11

It works like this: Everything that is between <template> and </template> is ignored by the browser when rendering the page. So far it works almost like a comment. But it has a difference: inside the tag template, you can by valid HTML, whose content will be completed by some script after the page is loaded.

That is: the template tag is used to declare HTML snippets that will be ignored by the browser, but will be available for use by scripts on that page. These scripts can, for example, retrieve the contents of the content attribute of the template object, and use the cloneNode - ex. Method:

function preenche() {
  var nomes = ["Bruno", "Daniel", "Marcelo"]
  var template = document.getElementsByTagName("template")[0];
  for (var i = 0; i < nomes.length; i++) {
    var texto = template.content.cloneNode(true);
    texto.querySelectorAll("spam")[0].textContent = nomes[i];
    document.body.appendChild(texto);
  }

}

preenche();
<body>
  <template>
           <p>
           Bem-vindo <spam></spam>
           </p>
       </template>


</body>

That is: you will only use if you are encoding Javascript that will populate, using DOM, not text replacement, values to appear on the page after it is loaded. In the above section, the names are pre-coded - but they can be obtained with an Ajax call.

In practice, in almost all pages and web applications we have created, or the server-side framework is that it generates formatted HTML, or javascript creates HTML from Ajax data using DOM, or text substitution. With the tag <template> , you can write a javascript cleaner to format the data obtained by ajax.

The official documentation for the template tag is here: link

    
20.06.2014 / 00:21