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.org.cn/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 编写