在 AMP 中获取动态数据

使用 amp-list 组件可以获取动态数据并展示


AMP 目前不支持添加自定义 JavaScript(目前不支持),所以不能通过发请求去获取数据

AMP 提供了一个叫 amp-list 的组件,可以通过它获取动态数据

使用

1
2
3
4
5
6
7
8
9
10
<amp-list width="auto"
height="100"
layout="fixed-height"
src="/static/inline-examples/data/amp-list-urls.json">
<template type="amp-mustache">
<div class="url-entry">
<a href="{{url}}">{{title}}</a>
</div>
</template>
</amp-list>

上面的代码中,将 amp-listsrc 属性设置成了数据获取地址

返回的数据必须是 json 格式,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"items": [
{
"title": "AMP YouTube Channel",
"url": "https://www.youtube.com/channel/UCXPBsjgKKG2HqsKBhWA4uQw"
},
{
"title": "AMPproject.org",
"url": "https://www.ampproject.org/"
},
{
"title": "AMP By Example",
"url": "https://ampbyexample.com/"
},
{
"title": "AMP Start",
"url": "https://ampstart.com/"
}
]
}

我们看到,在 response 最外层有一个 items 的属性

amp-list 默认会取这个 items 属性下的数组

如果你的目标数据所在的 key 不叫 items,则需要在 amp-list 上通过 items 属性进行指定:

1
2
3
4
5
6
7
//- pug

//- 目标数据放在 groups 下
amp-list(items="groups" src="xxx")

//- 如果 response 是嵌套的
amp-list(items="data.main.groups" src="xxx")

amp-mustache

对于数据的填充,AMP 使用的是 Mustache 的模版语法

比如说 遍历语法

1
2
3
{{#stooges}}
<b>{{name}}</b>
{{/stooges}}

*如果是在 pug 中使用,要将它们以文本形式输出,到了浏览器里 AMP 会去填充


single-item 属性

上面关于 AMP 使用的示例将数据数组交给了 amp-list

如果你想在 template 里去遍历数据的话,可以写成这样:

1
amp-list(items="data" single-item src="xxx")

single-item)会把 data 当作单元素数组交给 amp-list

An object response will be wrapped in an array so {items: {…}} will behave as if it were {items: [{…}]}


布局

amp-list 文档可以看到,其支持的 layouts 只有 fill, fixed, fixed-height, flex-item, nodisplay, responsive

如果你的元素高度是随内容变化(或者有具体的响应规则)的话,就比较难受,因为它不支持 container 这个 layout 类型


参考

原文作者: dgb8901,yinxing

原文链接: https://www.itwork.club/2019/08/01/AMP-get-dynamic-data/

版权声明: 转载请注明出处

为您推荐

体验小程序「简易记账」

关注公众号「特想学英语」

在 Google 搜索结果中展示表格