HTML <template>タグ


<template>を使用して、ページの読み込み時に非表示になるコンテンツを保持します。JavaScriptを使用して表示します。

<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>

以下の「自分で試してみてください」の例をもっと見てください。


定義と使用法

<template>タグは、ページの読み込み時にユーザーから非表示にされるHTMLコンテンツを保持するためのコンテナーとして使用されます

内部のコンテンツ<template>は、後でJavaScriptを使用してレンダリングできます。

<template>度も使用したいHTMLコードがある場合はタグを使用できますが、要求するまでは使用できません。タグなしこれを行う<template>には、ブラウザがコードをレンダリングしないように、JavaScriptを使用してHTMLコードを作成する必要があります。


ブラウザのサポート

Element
<template> 26.0 13.0 22.0 8.0 15.0

グローバル属性

<template>タグは、HTMLのグローバル属性をサポートます



その他の例

配列内のアイテムごとに1つの新しいdiv要素をWebページに入力します。各div要素のHTMLコードは、テンプレート要素内にあります。

<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>

<template>のブラウザサポートを確認してください。

<script>
if (document.createElement("template").content) {
  document.write("Your browser supports template!");
} else {
  document.write("Your browser does not supports template!");
}
</script>