【HTML】templateタグ - テンプレート

【HTML】templateタグ - テンプレート

HTMLのtemplateタグをご紹介します。

templateタグ

templateタグはHTML構造のテンプレートをマークアップします。
一般的にjavascriptでテンプレートを利用します。

基本構文

<template>コンテンツ</template>

サンプルコード

実行ボタンをクリックすると、JavaScriptでtemplate要素を複製し、表にデータを追加します。

<style>
    table { border-collapse: collapse ; }
    td,th { border: 1px solid black; }
</style>

<table>
    <thead>
        <tr>
            <th>商品</th>
            <th>値段</th>
        </tr>
    </thead>
    <tbody id="item-list">
    </tbody>
</table>

<template id="item-template">
    <tr>
        <td></td>
        <td></td>
    </tr>
</template>

<button id="action">実行</button>

<script type="text/javascript">
    var button = document.getElementById("action");
    button.addEventListener('click', function() {
        var list = document.getElementById("item-list");
        var template = document.getElementById("item-template");
        
        var items = [
            ["リンゴ", "¥300"],
            ["パイナップル", "¥1,000"],
            ["ブドウ", "¥2,500"],
        ];
        
        items.forEach( (item) => {
            var clone = template.content.cloneNode(true);
            var tds = clone.querySelectorAll("td");
            tds[0].textContent = item[0];
            tds[1].textContent = item[1];
            list.appendChild(clone);
        });
    });
</script>