动态更新 Feed 中的项目
简介
此示例演示了如何显示数据 Feed,允许用户在电子邮件中浏览大量项目而无需滚动。
该示例结合使用了 amp-list
(用于从服务器获取初始项目)和 amp-form
(用于通过发出新的服务器请求来“刷新”单个项目)。
样式
我们使用 CSS 在首次提交表单后隐藏最初获取的项目。
我们还定义了一个允许我们拥有固定卡片大小的布局,以确保表单提交不会导致内容跳动。
<style amp-custom>
.amp-form-submit-success .initial-content,
.amp-form-submitting .initial-content,
.amp-form-submit-error .initial-content {
display: none;
}
.card {
width: 160px;
height: 120px;
margin: 10px;
float: left;
position: relative;
}
.card .next-button {
position: absolute;
bottom: 0;
width: 100%;
}
</style>
单个项目模板
在卡片内部定义单个项目的模板并为其提供一个 id
。此模板由 amp-form
用于显示新项目。
在本例中,我们使用一个 amp-img
。
<template id="item-template" type="amp-mustache">
<amp-img src="{{items.imageUrl}}" layout="fixed" width="160" height="90"></amp-img>
</template>
初始项目列表
我们为初始项目及其布局定义一个模板并为其提供一个 id
,从而允许我们随后在 amp-list 中使用它。此模板由 amp-list
用于从服务器获取最新的初始内容。
它本身包含每个项目的 amp-form
,该表单引用其 id
所引用的上述模板。通过对 amp-form
使用不同的模板,我们可以“刷新”部分内容,在本例中为图像。
此模板包含与上述模板中用于渲染初始项目的标记 (在本例中为单个
amp-img
) 相同的标记。它包含在 <div class="initial-content">
中,该内容在用户首次提交表单时会变为隐藏。<template id="list-template" type="amp-mustache">
<form class="card" method="post" action-xhr="https://amp.org.cn/documentation/examples/api/photo-stream?single&width=160&height=90">
<div class="initial-content">
<amp-img src="{{imageUrl}}" layout="fixed" width="160" height="90"></amp-img>
</div>
<div submit-success template="item-template"></div>
<input class="next-button" type="submit" value="Next">
</form>
</template>
我们使用 amp-list
从服务器渲染初始项目,并使用其 id
引用的上述模板。
高度与我们的卡片及其边距的总高度相匹配。初始服务器响应定义要显示的卡片数量(在本例中为四个)。
<amp-list template="list-template" src="https://amp.org.cn/documentation/examples/api/photo-stream?width=160&height=90&items=4" layout="fixed" width="360" height="280">
</amp-list>
需要更多解释?
如果此页面上的解释未能涵盖您的所有问题,请随时与其他 AMP 用户联系,以讨论您的具体用例。
转到 Stack Overflow 未解释的功能?AMP 项目强烈鼓励您的参与和贡献!我们希望您能成为我们开源社区的持续参与者,但我们也欢迎您针对您特别感兴趣的问题做出一次性贡献。
在 GitHub 上编辑示例-
由 @fstanis 编写