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