amp-listで子要素の配列データを出力する
AMP用のコンポーネント「amp-list」で子要素の配列データを出力する方法です。
amp-listの中で別のamp-listを呼び出すことはできなかったので、一つのamp-listでitems配下の要素からさらに別の配列データを格納して表示します。
目次
- 準備
- データ
- コード
- 実際に出力されるHTML
- 参考リンク
準備
amp-listを利用する場合、以下の二つのライブラリを読み込みます。
<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属性で読み込むデータは以下の通り。
{
"categories":[
{
"id" : 1,
"name" : "カテゴリA",
"products" : [
{
"id" : 11,
"name" : "製品1A"
},
{
"id" : 12,
"name" : "製品1B"
}
]
},
{
"id" : 2,
"name" : "カテゴリB",
"products" : [
{
"id" : 21,
"name" : "製品2A"
},
{
"id" : 22,
"name" : "製品2B"
}
]
}
]
}
コード
上記データ(URLは仮にhttp://localhost/data/example.json)を読み込んで出力するamp-listのHTMLコード。
<amp-list layout="fixed-height"
height="200"
items="categories"
src="http://localhost/data/example.json">
<template type="amp-mustache">
<div class="category-product">
<div class="category-item">{{id}}:{{name}}</div>
<div class="product-items">
{{#products}}
<div class="product-item">{{id}}:{{name}}</div>
{{/products}}
</div>
</div>
</template>
</amp-list>
カテゴリの繰り返しは「items="categories"」で指定し、カテゴリ内の製品リストを「#products~/products」で指定しています。
実際に出力されるHTML
上記のコードを実行すると以下のようなHTMLが出力されます。
<amp-list layout="fixed-height" height="200" items="categories" 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="category-product" role="listitem">
<div class="category-item">1:カテゴリA</div>
<div class="product-items">
<div class="product-item">11:製品1A</div>
<div class="product-item">12:製品1B</div>
</div>
</div>
<div class="category-product" role="listitem">
<div class="category-item">2:カテゴリB</div>
<div class="product-items">
<div class="product-item">21:製品2A</div>
<div class="product-item">22:製品2B</div>
</div>
</div>
</div>
</amp-list>