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
Here’s a simple example
– Ivan Ferrer