AMP
  • 电子邮件

动态更新 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,该 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 上编辑示例