amp-mustache
簡介
amp-mustache
範本是以 mustache 為基礎的簡易結構化範本系統。
amp-mustache
實際上不提供資料或編譯範本。而是由其他 AMP 標籤(例如 amp-access
、amp-form
和 amp-list
)提供資料並編譯範本。如需這些使用案例的詳細資訊,請直接參閱這些文件/範例。
設定
匯入 amp-mustache
標籤。
<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
amp-mustache
需要與其他元件(例如 amp-list
或 amp-form
)一起使用。在本範例中,我們將使用 amp-list
。
<script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>
amp-mustache
範本的資料由其他 AMP 標籤提供。在本示範中,我們使用 amp-list
傳入 JSON 檔案,其中包含如下所示的字典
{ "items": [ { "fullname": "John Doe", "phonenumber": "212-555-1212", "cart_items": [ { "name": "Pluot", "quantity": 5, "price": "$1.00" }, { "name": "Apple", "quantity": 1, "price": "$3.25" } ], "address": { "addr1": "111 8th Ave", "city": "New York", "state": "NY", "zipcode": 10011 } } ] }
變數
當變數名稱以雙大括號 ({{varname}}
) 括住時,變數會被內插。
<amp-list src="/static/samples/json/cart.json" layout="fixed-height" height="56" binding="no">
<template type="amp-mustache">
Hi {{fullname}}!
</template>
</amp-list>
條件式
條件式使用相同的語法呼叫,但會在前面加上井字號 (#
)。
<amp-list src="/static/samples/json/cart.json" layout="fixed-height" height="56" binding="no">
<template type="amp-mustache">
{{#phonenumber}}
The registered phone number is {{phonenumber}}
{{/phonenumber}}
</template>
</amp-list>
負條件式
若要使用負條件式,請在變數名稱前插入插入符號 (^
)。
<amp-list src="/static/samples/json/cart.json" layout="fixed-height" height="56" binding="no">
<template type="amp-mustache">
{{^twitter}}
There is no registered twitter account for this profile
{{/twitter}}
</template>
</amp-list>
迴圈
迴圈使用與條件式相同的語法,但適用於提供清單而非純量變數(例如字串、整數和字典)的情況。
{{#cart_items}}
{{name}} {{quantity}} {{price}}
{{/cart_items}} {{^cart_items}}您的購物車是空的!
{{/cart_items}}<amp-list src="/static/samples/json/cart.json" layout="fixed-height" height="80" binding="no">
<template type="amp-mustache">
<div id="cart">
{{#cart_items}}
<div class="cart-item">
<span>{{name}}</span>
<span>{{quantity}}</span>
<span>{{price}}</span>
</div>
{{/cart_items}}
{{^cart_items}}
<div>Your cart is empty!</div>
{{/cart_items}}
</div>
</template>
</amp-list>
需要更多說明嗎?
如果此頁面上的說明未涵蓋您的所有問題,請隨時與其他 AMP 使用者聯絡,討論您的確切使用案例。
前往 Stack Overflow 未說明的特色功能?AMP 專案大力鼓勵您的參與和貢獻!我們希望您能成為我們開放原始碼社群的長期參與者,同時我們也歡迎您針對您特別關注的問題做出一次性貢獻。
在 GitHub 上編輯範例-
由 @jmadler 撰寫