3
4

More than 3 years have passed since last update.

templateをtemplateらしく使う

Last updated at Posted at 2021-07-15
index.html
<template></template>

テンプレートタグなるものを使いたいとき、調べた限りだとcloneして要素にデータを挿入してappendChildするように、ということだった。
参考 : Qiita - template要素の使い方、知ってます?
この「要素にデータを挿入」の処理が気に入らず、テンプレートらしく使う方法を考えたのでメモ。

templateをこういう感じで書きたい

index.html
<ul id="my_list">
    <template id="my_template">
        <li class="{{class_name}}">
            <a href="{{url}}">
                <h1>{{title}}</h1>
                <p>{{text}}</p>
            </a>
        </li>
    </template>
    <!--ここにリストを追加したい-->
</ul>

こんな感じで書けばいけました

template_to_html.js
var obj = { //追加したいデータ
    class_name: 'list_item',
    url: 'https://qiita.com',
    title: 'タイトル',
    text: '本文'
};

//テンプレートから書き込みデータを作成
function template_to_html(template_id,obj){
    //文字列としてテンプレートのinnerHTMLを取得
    var str = $(template_id)[0].innerHTML;
    //{{}}で囲まれた文字列を検索するための正規表現
    var reg = /{{[a-zA-Z1-9_\-]*}}/g;
    var arr,replaced = str;
    while((arr = reg.exec(str))!==null){
        //{{}}で囲まれた文字列をobjのキーとして置換
        var key = arr[0].replace('{{','').replace('}}','');
        replaced = replaced.replace(arr[0],obj[key]);
    };
    return replaced;
};

//書き込み処理
$('ul#my_list').append(template_to_html('#my_template',obj));

実行結果

result.html
<ul id="my_list">
    <template id="my_template">
        <!-- 中略 -->
    </template>
    <!--こういう感じで追加される-->
    <li class="list_item">
        <a href="https://qiita.com">
            <h1>タイトル</h1>
            <p>本文</p>
        </a>
    </li>
</ul>

補足

  • objのキーと{{}}内の文字列を揃えるのが大事。
  • objを配列に入れて、書き込み処理をぐるぐる回せば連続で追加できる。
  • 正規表現の書き方とかreplaceの仕方とかもっとスマートな書き方があるかも。innerHTMLで文字列として取得して置き換えるというのがポイント。
  • appendのところをjQuery使わずにappendChildとすると、文字列として挿入されてしまう。htmlとして挿入できれば、脱jQueryも可。

修正

  • 21/7/16 11:00 正規表現で-と_を使えるように修正しました。
3
4
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4