template要素と不活性コンテンツ
有効化されるまで解析のみ行われ、描画されないHTMLを定義します
「template要素と不活性コンテンツ」はCoddyKit上の無料HTML Academyレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはHTML Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 HTML Academyコースには全4レッスンが含まれています。
template要素とは
<template>要素には、解析されますがレンダリングされないHTMLを保持します。
- コンテンツはDOM内にありますが、表示されません
- 内部のスクリプトは実行されません
- 画像は読み込まれません
- CSSは適用されません
- クローンされるまで「不活性」です
templateの基本的な使い方
templateを定義し、そのコンテンツを確認します。
<template id="card-template">
<div class="card">
<h2 class="card-title"></h2>
<p class="card-body"></p>
<a class="card-link">Learn more</a>
</div>
</template>
<script>
const tmpl = document.getElementById('card-template');
console.log(tmpl.content); // DocumentFragment
console.log(tmpl.content.querySelector('.card')); // The div node
// Not rendered on the page yet
</script>template.content
.contentプロパティはDocumentFragmentを返します。
const template = document.querySelector('#card-template');
const fragment = template.content;
// fragment is a DocumentFragment — a lightweight DOM container
// It is not attached to the document
// Modifying fragment does NOT affect the original template
// You must clone it before using ittemplateのクローン作成
cloneNode(true)を使用して、templateのコンテンツのコピーを作成します。
const tmpl = document.getElementById('card-template');
const clone = tmpl.content.cloneNode(true); // true = deep clone
// Modify the clone:
clone.querySelector('.card-title').textContent = 'HTML5 Guide';
clone.querySelector('.card-body').textContent = 'Learn HTML5 from scratch.';
clone.querySelector('.card-link').href = '/html5';
// Add to the page:
document.getElementById('card-list').appendChild(clone);templateからリストをレンダリングする
1つのtemplateから複数の項目を生成します。
<ul id="users"></ul>
<template id="user-tmpl">
<li class="user">
<strong class="user-name"></strong>
<span class="user-role"></span>
</li>
</template>
<script>
const tmpl = document.getElementById('user-tmpl');
const list = document.getElementById('users');
const users = [
{ name: 'Alice', role: 'Admin' },
{ name: 'Bob', role: 'Editor' },
];
users.forEach(user => {
const clone = tmpl.content.cloneNode(true);
clone.querySelector('.user-name').textContent = user.name;
clone.querySelector('.user-role').textContent = user.role;
list.appendChild(clone);
});
</script>innerHTMLではなくtemplateを使う理由
templateはinnerHTMLよりも安全で効率的です。
// innerHTML approach (less safe):
container.innerHTML = `<div>${userProvidedContent}</div>`;
// Risk: XSS if userProvidedContent is not sanitized
// template approach (safer):
const clone = tmpl.content.cloneNode(true);
clone.querySelector('.name').textContent = userProvidedContent;
// textContent sets text only — HTML tags are not parsed
// No XSS riskネストしたデータを持つtemplate
ネストした構造を持つ複雑なtemplateです。
<template id="post-tmpl">
<article>
<header>
<h2 class="title"></h2>
<time class="date" datetime=""></time>
</header>
<p class="excerpt"></p>
<a class="read-more">Read more</a>
</article>
</template>
<script>
function renderPost(post) {
const clone = document.getElementById('post-tmpl').content.cloneNode(true);
clone.querySelector('.title').textContent = post.title;
clone.querySelector('.date').textContent = post.date;
clone.querySelector('.date').dateTime = post.isoDate;
clone.querySelector('.excerpt').textContent = post.excerpt;
clone.querySelector('.read-more').href = post.url;
return clone;
}
</script>templateはレンダリングされない
templateのコンテンツがユーザーから見えないことを確認します。
<template id="hidden-tmpl">
<script>alert('This runs when cloned, not when defined');</script>
<img src="wont-load-yet.jpg" alt="Won't load until cloned">
</template>
<!-- The script and image are NOT activated until you clone and append the template -->
<!-- This makes templates safe for defining content without side effects -->templateとscript type=text/htmlの比較
従来のパターンと、現代的なtemplateを比較します。
<!-- Old pattern (script hack): -->
<script type="text/html" id="old-tmpl">
<div class="card">...</div>
</script>
<script>
const html = document.getElementById('old-tmpl').innerHTML;
container.innerHTML = html; // XSS risk!
</script>
<!-- Modern template: -->
<template id="card-tmpl">...</template>
<!-- Safer, semantic, no XSS risk -->コンポーネントライブラリでのtemplate
vanillaのコンポーネントライブラリで使うtemplateのパターンです。
class UserCard extends HTMLElement {
connectedCallback() {
const tmpl = document.getElementById('user-card-tmpl').content.cloneNode(true);
tmpl.querySelector('.name').textContent = this.getAttribute('name');
this.appendChild(tmpl);
}
}確認問題
cloneNode(true)は、templateのcontentプロパティに対して何を行いますか?
まとめ:template要素
templateの要点:
- 不活性なHTML — 解析されますが、レンダリングされません
template.content— DocumentFragmentを返しますcontent.cloneNode(true)— 深いコピーを作成し、変更や追加が可能な状態にします- innerHTMLより安全 — textContentを使うため、HTMLインジェクションが発生しません
- カスタム要素、繰り返し使うUIパターン、Web Componentsで使用されます
よくある質問
「template要素と不活性コンテンツ」レッスンは無料ですか?
はい。「template要素と不活性コンテンツ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、HTML Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 HTML Academyコースには全4レッスンが含まれています。
「template要素と不活性コンテンツ」で何を学びますか?
有効化されるまで解析のみ行われ、描画されないHTMLを定義します ブラウザで直接実行するハンズオンコードでHTML Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
HTML Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのHTML Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。
「template要素と不活性コンテンツ」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このHTML Academyレッスンでコードを書いて実行できますか?
はい。すべてのHTML Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。