2017.11.22

amp-bindで動的にCSSクラスを設定する

AMP用のコンポーネント「amp-bind」を使って特定の要素に対して動的にCSSクラスを設定する方法です。

「amp-bind」を利用することでJavaScriptが使えないAMPでも、ある程度の動的なコンテンツが作成できます。

目次

  • 準備
  • データ
  • コード
  • 実際に出力されるHTML
  • 参考リンク

準備

今回はamp-bind以外にamp-listも利用するので、以下のライブラリを読み込みます。


<script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
<script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>
<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.1.js"></script>

データ

amp-listのsrc属性で読み込むデータは以下の通り。


{
    "items":[
        { 
            "id" : 1, 
            "name" : "アイテムA" 
        },
        { 
            "id" : 2, 
            "name" : "アイテムB" 
        },
        { 
            "id" : 3, 
            "name" : "アイテムC" 
        }
    ]
}

コード

上記データ(URLは仮にhttp://localhost/data/example.json)を読み込んで出力するamp-listのHTMLコード。


<amp-list layout="fixed-height"
          height="200"
          src="http://localhost/data/example.json">
    <template type="amp-mustache">
        <div [class]="{{id}} == 2 ? 'active' : ''">{{name}}</div>
    </template>
</amp-list>

amp-bindのコードは[class]と指定している箇所。

実際に出力されるHTML

上記のコードを実行すると以下のようなHTMLが出力されます。


<amp-list layout="fixed-height" height="200" src="http://localhost/data/example.json" class="i-amphtml-element i-amphtml-layout-fixed-height i-amphtml-layout-size-defined i-amphtml-layout" aria-live="polite" style="height: 200px;">
    <div class="i-amphtml-fill-content i-amphtml-replaced-content" role="list">
        <div [class]="1 == 2 ? 'active' : ''" class="" role="listitem">アイテムA</div>
        <div [class]="2 == 2 ? 'active' : ''" class="active" role="listitem">アイテムB</div>
        <div [class]="3 == 2 ? 'active' : ''" class="" role="listitem">アイテムC</div>
    </div>
</amp-list>

itemsのidが2のデータのみclassに「active」が設定されています。

参考リンク

AMP】関連記事