mustache - 有没有办法在 mustache 迭代中设置计数器?

标签 mustache

我有一个代码,它呈现了一个带有一些迭代的 mustache 模板,例如:

{{#items}}
  some html code....
{{/items}}

但我想将渲染的项目数放入迭代中,如下所示:
{{#items}}
  This is the item [COUNTER-VAR]
{{/items}}

有一些方法可以执行此操作......?

最佳答案

不再需要 Handlebars 。您可以使用当前 mustache 中的高阶部分。这些基本上允许您使用该部分的内容作为参数调用函数。如果该部分在迭代中,它将为迭代中的每个项目调用。

鉴于此模板(为了方便和清晰,保留在脚本标签中)

<script type="text/html" id="itemview">
    <table width="100%" border="0" cellspacing="0" cellpadding="3">
        <tbody>
            {{#items}}
                <tr>
                    <td>{{#count}}unused{{/count}}</td>
                    <td>{{.}}</td
                </tr>
            {{/items}}
        </tbody>
    </table>
</script>

...以及以下代码,您可以构建一个编号列表。
function buildPage(root)
{
    var counter = 0;
    var data = {
        'items': [ 'England', 'Germany', 'France' ],

        'count' : function () {
            return function (text, render) {
                // note that counter is in the enclosing scope
                return counter++;
            }
        }
    };

    // fetch the template from the above script tag
    var template = document.getElementById('itemview').innerHTML;
    document.getElementById("results").innerHTML = Mustache.to_html(template, data);
}

输出:
0 英格兰
1 德国
2 法国

关于mustache - 有没有办法在 mustache 迭代中设置计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4592491/

相关文章:

javascript - 如何更改 Mustache.js 中的不转义 HTML 定界符

java - mustache 模板不会使用 dropwizard 进行更新

java - mustache :如何在 Java 中创建自定义辅助函数

ruby - 使用 Mustache Ruby API 提取键名?

javascript - jQuery Mustache 不适用于 IE 8

mustache - 在 Mustache 模板中,是否有一种优雅的方式来表达逗号分隔的列表而无需尾随逗号?

javascript - 渲染示例数据时未显示 "Mustache.js"

javascript - 如何将 id 转换为小写?

arrays - mustache - 如何检测数组不为空?

Jquery clone() 似乎不适用于 Mustaches