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