AMP Mustache 模板 {{name}} 未渲染 JSON 响应中的数据

问题描述 投票:0回答:1

我正在开发一个 AMP 页面,其中使用 amp-list 和 Mustache 模板来显示来自 JSON 响应的数据。来自服务器的 JSON 响应是正确的,并且包含名称字段,但 Mustache 模板中的 {{name}} 占位符不会呈现任何数据。

JSON 响应

{
"items": [
    {"name": "London, England"},
    {"name": "London"},
    {"name": "City of London, England"},
    {"name": "Londonderry, Northern Ireland"}
]

}

AMP HTML 代码:

<amp-list width="auto" height="100" layout="fixed-height" 
      src="https://example.com/index.php?route=information/places/search" 
      [src]="'https://example.com/index.php?route=information/places/search&q=' + query">
<template type="amp-mustache">
    <div class="autocomplete-suggestion" role="button" tabindex="0">
        Name: {{name}}
    </div>
</template>
<div placeholder>Loading...</div>
<div fallback>No results found.</div>

页面验证为 AMP,网络选项卡显示正确的 JSON 响应。输入根据输入的值显示响应式下拉列表,但模板中的 {{name}} 字段不显示任何数据。这可能是在控制器上获取数据并将其传递到视图时出现的服务器端问题,还是我在 AMP 设置中缺少某些内容?

任何见解将不胜感激!

amp-html amp-list amp-mustache
1个回答
0
投票

原因:

该问题是由我的框架中的 Twig 模板引擎引起的,该引擎使用与 AMP 的 Mustache 相同的 {{ ... }} 语法进行变量插值。 Twig 在到达 Mustache 模板之前正在处理 {{name}} 变量,导致它们无法渲染。

解决方案:

为了防止 Twig 解释 Mustache 语法,我将 Mustache 模板包装在 {% verbatim %} 块中。这告诉 Twig 忽略块内的所有内容并将其视为纯文本,从而允许 Mustache 正确处理变量。

真心希望这对其他人有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.