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