Tag <template> HTML

Definition and usage

<template> Tags are used as containers to hide some HTML content from the user when the page is loaded.

<template> The content inside can be displayed later using JavaScript.

If you have some HTML code that you want to reuse but only display when needed, you can use <template> Tags. If there is no <template> Tags, you need to use JavaScript to create HTML code to prevent the browser from rendering the code.

Example

Example 1

Using <template> To save some content that will be hidden when the page is loaded, and use JavaScript to display it:

<button onclick="showContent()">Show hidden content</button>
<template>
  <h2>Flower</h2>
  <img src="img_white_flower.jpg" width="214" height="204">
</template>
<script>
function showContent() {
  var temp = document.getElementsByTagName("template")[0];
  var clon = temp.content.cloneNode(true);
  document.body.appendChild(clon);
}
</script>

Spróbuj sam

Example 2

For each item in the array, fill the web page with a new div element. The HTML code for each div element is in the template element:

<template>
  <div class="myClass">I like: </div>
</template>
<script>
var myArr = ["Audi", "BMW", "Ford", "Honda", "Jaguar", "Nissan"];
function showContent() {
  var temp, item, a, i;
  temp = document.getElementsByTagName("template")[0];
  item = temp.content.querySelector("div");
  for (i = 0; i < myArr.length; i++) {
    a = document.importNode(item, true);
    a.textContent += myArr[i];
    document.body.appendChild(a);
  }
}
</script>

Spróbuj sam

Przykład 3

Sprawdź, czy przeglądarka obsługuje <template> obsługa:

<script>
if (document.createElement("template").content) {
  document.write("Twoja przeglądarka obsługuje szablony!");
} else {
  document.write("Twoja przeglądarka nie obsługuje szablonów!");
}
</script>

Spróbuj sam

Globalne atrybuty

<template> Tagi obsługują również Globalne atrybuty HTML.

Obsługa przeglądarek

Liczby w tabeli wskazują na wersję pierwszego przeglądarki, która w pełni obsługuje tę właściwość.

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
26.0 13.0 22.0 8.0 15.0