javascript - Mustache 平面数组到嵌套元素中

标签 javascript json template-engine mustache

我正在隔离问题并在此处创建一个简单的案例。它基本上是一个图像 Accordion (基于 CSS3 动画),为了使用这个插件,我的 HTML 结构必须嵌套,如下所示。在他们的示例中,HTML 是硬编码的 - 我需要使用 JSON 数据来生成输出。

假设有一个像这样的对象,

[{imageurl:"link1"}, {imageurl: "link2"}, {imageurl: "link3"}]

我想要的输出是

<figure>
    <img src="link1" />
    <figure>
        <img src="link2" />
        <figure>
           <img src="link3 />
        </figure>
    </figure>
 </figure>

我正在思考什么样的模板可以帮助实现这一目标?

最佳答案

由于 Mustache 语言是“无逻辑”的,因此需要逻辑或复杂嵌套的 View 可能需要分解为不同的 View 并通过部分 View 包含或在 Mustache 外部创建然后重新插入。

无论如何,产生您想要的 View 的一种方法是反转数组并从内到外嵌套数字( jsfiddle ):

<!-- If your desired output is so:
<figure>
    <img src="link1">
    <figure>
        <img src="link2">
        <figure>
           <img src="link3">
        </figure>
    </figure>
 </figure>
-->
<script id="entriesTemplate" type="text/x-mustache-template">
    <figure>
        <img src="{{{imageurl}}}">
        {{{figure}}}
    </figure>
</script>

然后您可以通过一小段 JS 嵌套上述模板:

var figs = [
    {url: "http://placehold.it/10x10"},
    {url: "http://placehold.it/10x10"},
    {url: "http://placehold.it/10x10"}
];

var ft = document.querySelector('#entriesTemplate').innerText.trim();
Mustache.parse(ft);

console.log(
    figs.slice(0) // Make a copy of the array as the next call to `.reverse()` will work in situ
        .reverse()
        .reduce(function (previous, current, index, array) {
            return fig = Mustache.render(ft, {
                imageurl: current.url,
                figure: previous
            });
        }, undefined)
);

当您将 undefined 传递到第一个模板渲染时,Mustache 将不会生成嵌套图形。每次后续渲染,您都将过去的输出传递到外部图形等。您可以根据需要插入 HTML block ,而不是记录值。

关于javascript - Mustache 平面数组到嵌套元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23704828/

相关文章:

json - 如何使用 SWIFT 通过 JSON 将数据从多个 View Controller POST 到服务器

java - Jackson 在反序列化期间设置值

python - 使用 Mechanize 和 Python Django View 解析 JSON 输出

node.js - 使用 Node.js 复制和转换文件

java - 如何在 liferay 的速度模板中创建 sortedmap 或 treemap

javascript - 消息 "Request for font "Noto Sans“在可见性级别 1 被阻止(需要 3)-node.js”意味着什么以及如何防止它?

javascript - 将鼠标悬停在一个 div 上,影响另一个 div 中图像的不透明度(使用 jquery)

javascript - (Google 跟踪代码管理器)GTM 增强型电子商务结帐步骤不跟踪

GWT JSNI 中的 Javascript 条件编译

java - Java 模板引擎中 URL 的最佳实践