16

我有一个代码可以渲染一个带有一些迭代的小胡子模板,例如:

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

但我想将渲染的项目数放入迭代中,如下所示:

{{#items}}
  This is the item [COUNTER-VAR]
{{/items}}

有一些方法可以执行这个..??

4

4 回答 4

16

不再需要车把。您可以使用当前小胡子中的高阶部分。这些基本上可以让你调用一个以该部分的内容作为参数的函数。如果该部分在迭代中,它将为迭代中的每个项目调用。

给定这个模板(为了方便和清晰,保留在脚本标签中)

<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 法国

于 2011-07-07T23:48:08.343 回答
8

在迭代中使用 {{@index}}。

{{#data}}
    <p>Index is {{@index}}</p>
{{/data}}
于 2016-03-21T14:02:01.747 回答
0

您可以使用车把扩展来留胡子并编写一个辅助函数来碰撞计数器。

我在这里做了更多的解释。 在 Mustache 中,如何获取当前 Section 的索引

于 2011-02-22T03:23:27.010 回答
0

或者,只需在您的数组中添加一个计数器......我知道这是一个丑陋的解决方案,但它是最易读的并且可以完成工作。

const myData = ["Alpha", "Bravo", "Charlie", "Delta", "Echo"];

tags.myArr = [];
for (let i = 0; i < myData.length; i++) {
  tags.myArr.push({index: i, data: myData[i]});
}
return Mustache.render(template, tags);
{{#myArr}}
  Number {{index}}: {{data}}
{{/myArr}}
于 2020-04-07T02:43:02.697 回答