LoginSignup
3
5

More than 5 years have passed since last update.

HTML5 templateタグを記述する

Posted at

以前Lightningコンポーネント内にscriptタグを記述する方法というネタ的な投稿にてaura:htmlタグを紹介しましたが、aura:htmlタグにはタグ名のチェックを回避してくれる場合がある、というポイントがあります。

ここでは、HTML5で導入されたtemplateタグを記載してみましょう。templateタグについてざっくり言うと、HTMLの断片をJavaScriptからテンプレート的に使う時にdivの代わりに使えるタグです。

Template.cmp
<aura:html tag=“template” id=“mytemplate”>
  <!– template body goes here -->
  <div>Template used: <span>0</span></div>
</aura:html>
TemplateController.js
({
    useIt: function() {
        var div = document.querySelector('template div');
        // Update something in the template DOM.
        var span = div.querySelector('span');
        span.textContent = parseInt(span.textContent) + 1;
        document.querySelector('#container').appendChild(
            document.importNode(div, true));   
    }
})

ボタンを何度も押すと、templateタグの中身が複製されていきます。

スクリーンショット 2015-01-28 15.32.57.png

ここで注意点として、Lightningではタグの記載に応じて動的にDOMを構築していくため、コンポーネントファイルに記載したDOMの構造と実際の構造が変わっていくことがあります。冒頭の記事の通り、scriptは特殊処理が行われるのでtemplateタグ内でも実行されてしまいますが、それに限らず、意図と違う動作になった場合にはDOM構造を確認すると良いでしょう。

3
5
0

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
5