How does the HTML5 <template> element work?

Asked

Viewed 1,965 times

14

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

Apparently it allows the creation of custom tags, more or less like in XML:

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

But it’s not yet clear to me what exactly it brings benefits and to what extent this tag creation allows you to go.

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

1 answer

12


Here’s how it works: All that stands between <template> and </template> is ignored by the browser when rendering the page. Up to there it works almost as if it were a comment. Only it has a difference: inside the template tag, you can by valid HTML, whose content will be completed by some script after the page is loaded.

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

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>

In other words: you will only use it if you are coding Javascript that you will fill, using DOM, and not replacing texts, 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 every web page and application we create, either the server-side framework generates formatted HTML, or javascript creates the HTML of Ajax data using DOM, or text substitution. Tagged <template>, can write a cleaner javascript to format the data obtained by ajax.

The official tag documentation template is here: http://www.w3.org/TR/html/scripting-1.html#the-template-element

Browser other questions tagged

You are not signed in. Login or sign up in order to post.