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 撰写