トップページ  > HTML Living Standard  > <template>

★HTML Living Standard リファレンス

<template> …… テンプレートを表す
Internet Explorer Microsoft Edge Google Chrome Safari Firefox Opera
広告

<template>タグは、テンプレートを表す際に使用します。

template要素は、スクリプトで作成したデータをドキュメントに挿入するためのテンプレートを宣言します。 ここでいうテンプレートとは、HTMLの断片のことです。

template要素の内容は、template要素の子ではありません。 それは、あくまでもテンプレートとして宣言されたHTMLの断片です。 各template要素には、そのテンプレート内容であるDocumentFragmentオブジェクトが関連付けられています。

template要素自体は、レンダリングでは何も表しません。

■使用例

以下のサンプルは、template要素を使用して <p>Smile!</p> というHTMLの断片を宣言しています。 template要素内のp要素は、DOMにおけるtemplate要素の子ではなく、あくまでも宣言されたHTMLの断片です。

HTMLソース

<!doctype html>
<html lang="en">
 <head>
  <title>Homework</title>
 <body>
  <template id="template"><p>Smile!</p></template>
  <script>
   let num = 3;
   const fragment = document.getElementById('template').content.cloneNode(true);
   while (num-- > 1) {
     fragment.firstChild.before(fragment.firstChild.cloneNode(true));
     fragment.firstChild.textContent += fragment.lastChild.textContent;
   }
   document.body.appendChild(fragment);
  </script>
</html>
↓↓↓

ブラウザ上の表示

別画面で開く

■使用例

以下のサンプルは、template要素でテンプレートを用意して、そこへデータを流し込んでいます。

HTMLソース

<!DOCTYPE html>
<html lang="ja">
<meta charset="UTF-8">
<title>猫のデータ</title>

<script>
 var data = [
   { name: 'モモ', color: 'ハチワレ', sex: 'メス' },
   { name: 'おはぎ', color: 'キジトラ', sex: 'オス' },
 ];
</script>

<table>
 <thead>
  <tr>
   <th>名前 <th>毛色 <th>性別
 <tbody>
  <template id="row">
   <tr><td><td><td><td>
  </template>
</table>

<script>
 var template = document.querySelector('#row');
 for (var i = 0; i < data.length; i += 1) {
   var cat = data[i];
   var clone = template.content.cloneNode(true);
   var cells = clone.querySelectorAll('td');
   cells[0].textContent = cat.name;
   cells[1].textContent = cat.color;
   cells[2].textContent = cat.sex;
   template.parentNode.appendChild(clone);
 }
</script>

</html>
↓↓↓

ブラウザ上の表示

別画面で開く

広告
Sponsors
広告
MuuMuu Domain!
ドメイン取るならお名前.com
現役エンジニアのオンライン家庭教師【CodeCamp】
サイトに広告を掲載してお小遣いが稼げる!【A8.net】
Node.jsコース
はじめてのプログラミングコース
▲ページ先頭へ
HTMLクイックリファレンスについて
© HTMQ