amp-render
簡介
<amp-render>
元件提供了一種簡單的方式,可從伺服器載入 JSON,並使用 mustache 範本 進行轉譯。
設定
首先,您需要匯入 amp-render
擴充功能的指令碼。
<script async custom-element="amp-render" src="https://cdn.ampproject.org/v0/amp-render-1.0.js"></script>
當您使用 amp-render
時,幾乎可以肯定也會想要使用 amp-mustache
。
<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
在此頁面的最後範例中,我們也會使用 amp-script
,因此我們也會匯入該擴充功能的指令碼。
<script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>
基本範例
這是一個基本範例,將簡單的範本套用至簡單的 JSON 物件。JSON 看起來像這樣
{ "country": "Nigeria", "city": "Lagos" }
以下是 <amp-render>
和 <template>
<amp-render class="sample" src="/static/samples/json/cities-lagos.json" layout="fixed-height" height="60">
<template type="amp-mustache">
<div class="line">{{city}} is a city in {{country}}.</div>
</template>
</amp-render>
迭代列表
在此範例中,我們向下鑽研以存取更精細 JSON 的子物件。然後,我們的範本會迭代子物件所包含陣列的元素。
<amp-render class="sample" src="/static/samples/json/cities.json" layout="fixed-height" height="105">
<template type="amp-mustache">
{{#planets}}
{{#earth}}
{{#continents}}
{{#africa}}
<div class="line">{{city}} is a city in {{country}}.</div>
{{/africa}}
{{/continents}}
{{/earth}}
{{/planets}}
</template>
</amp-render>
使用更多屬性
現在,讓我們嘗試更多屬性。
-
binding:
binding="never"
告訴 AMP,此範本中不需要評估amp-bind
繫結。這樣效率更高,尤其因為我們的範本不包含任何繫結。 -
key:這可讓我們選擇 JSON 物件的子項,並將其套用至範本,而不是整個物件。
-
template:這可讓我們指定一個不是
amp-render
子項的範本。
<amp-render class="sample" src="/static/samples/json/cities.json" layout="fixed-height" height="105" binding="never" key="planets.earth.continents" template="cities-countries">
</amp-render>
<template id="cities-countries" type="amp-mustache">
{{#africa}}
<div class="line">{{city}} is a city in {{country}}.</div>
{{/africa}}
</template>
使用 amp-script
amp-render
也可以使用 amp-script
作為資料來源。在此範例中,我們未使用 key
屬性,而是使用我們自己的 JavaScript 擷取城市資料,然後擷取所需的子物件。若要進一步瞭解如何使用 amp-script
擷取資料,請參閱 此 amp-script
範例。
<amp-render class="sample" src="amp-script:dataFunctions.fetchData" layout="fixed-height" height="52">
<template type="amp-mustache">
{{#southAmerica}}
<div class="line">{{city}} is a city in {{country}}.</div>
{{/southAmerica}}
</template>
</amp-render>
<amp-script id="dataFunctions" script="fetch-data-script" nodom></amp-script>
<script id="fetch-data-script" type="text/plain" target="amp-script">
function fetchData(index) {
return fetch('https://amp.dev.org.tw/static/samples/json/cities.json')
.then(resp => resp.json())
.then(findContinentsData)
}
function findContinentsData(json) {
return json.planets.earth.continents;
}
exportFunction('fetchData', fetchData);
</script>
如果此頁面上的說明未涵蓋您的所有問題,請隨時與其他 AMP 使用者聯絡,以討論您的確切使用案例。
前往 Stack Overflow 未說明的特色功能?AMP 專案大力鼓勵您的參與和貢獻!我們希望您能成為我們開放原始碼社群的持續參與者,但我們也歡迎針對您特別熱衷的問題提供一次性貢獻。
在 GitHub 上編輯範例-
由 @morss 撰寫