AMP

使用新的 amp-render 简化获取和渲染

网站

今天,我们很高兴推出 AMP 的一个全新组件:<amp-render>!

<amp-render> 使获取和渲染数据变得简单。首先,它从 URL、状态变量或 <amp-script> 中获取数据 - 由您选择。然后,它将此数据应用于您指定的 mustache 模板,并在您的网页上显示结果。

它是如何工作的?

那么 - 您如何使用 <amp-render>

让我们从 一个基本示例 开始。此组件使用 “src” 属性 请求包含城市名称及其关联国家的数据,然后显示该城市和国家。

<amp-render src="cities-lagos.json" layout="fixed-height" height="60">
      <template type="amp-mustache">
        <div>{{city}} is a city in {{country}}.</div>
      </template>
    </amp-render>Code language: HTML, XML (xml)

此示例 使用了 amp-render 的更多属性。它使用 “key” 属性 访问 JSON 中节点 planets.earth.continents 的子树并进行渲染。它还使用 “template” 属性 使用具有 id “cities-countries” 的单独模板元素进行渲染。

      <amp-render
        src="cities.json"
        key="planets.earth.continents"
        template="cities-countries"
        layout="fixed-height"
        height="105"
      >
      </amp-render>

      <template id="cities-countries" type="amp-mustache">
        {{#africa}}
          <div>{{city}} is a city in {{country}}.</div>
        {{/africa}}
      </template> Code language: HTML, XML (xml)

此最终示例 展示了如何使用 <amp-script> 使用自定义 JavaScript 获取数据。我们没有使用 “key” 属性来定位所需的数据子树,而是使用我们自己的代码。这使我们能够在将数据应用于模板之前在客户端对数据进行处理。

      <amp-render
        src="amp-script:dataFunctions.fetchData"
        layout="fixed-height"
        height="52"
      >
        <template type="amp-mustache">
          {{#southAmerica}}
            <div>{{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('cities.json')
            .then(resp => resp.json())
            .then(findContinentsData)
        }
      
        function findContinentsData(json) {
          return json.planets.earth.continents;
        }
      
        exportFunction('fetchData', fetchData);
      </script>Code language: HTML, XML (xml)

同样,您可以使用辅助 <amp-script> 来过滤数据、清理数据、创建无限列表功能等等。

与 <amp-list> 的比较

您可能会问 - 但 <amp-list> 不是已经可以获取和渲染数据了吗?

<amp-render> 与 <amp-list> 并存,AMP 开发人员一直使用该组件来 从 2015 年(AMP 诞生的年份)开始获取和渲染数据<amp-list> 非常适合渲染任何类型的基于列表的内容。它还支持无限滚动等功能,或者如果您需要专门为处理列表而设计的内置功能。对于更简单的界面、非列表形式的数据、处理动态内容大小(即将推出)或您希望使用自己的 JavaScript 控制行为的情况,我们建议使用 <amp-render>

即将推出

AMP 团队正在努力支持 layout=”container”,使该组件能够动态调整大小以适应渲染的内容。 <amp-render> 还将支持 resizeToContents 操作;触发此操作将调整组件的大小以适应内容。这些功能将很快推出。

您今天就可以尝试使用 <amp-render>!要了解更多信息,请查看 文档。与往常一样,如果您有任何反馈或功能请求,请 告诉我们

作者:Ben Morss,AMP 项目开发者倡导者,以及 Dhruv Manek,AMP 项目软件工程师