【发布时间】:2011-01-04 10:14:56
【问题描述】:
我有一个代码可以渲染一个带有一些迭代的小胡子模板,例如:
{{#items}}
some html code....
{{/items}}
但我想将渲染的项目数放入迭代中,如下所示:
{{#items}}
This is the item [COUNTER-VAR]
{{/items}}
有一些方法可以执行此操作..??
【问题讨论】:
标签: mustache
我有一个代码可以渲染一个带有一些迭代的小胡子模板,例如:
{{#items}}
some html code....
{{/items}}
但我想将渲染的项目数放入迭代中,如下所示:
{{#items}}
This is the item [COUNTER-VAR]
{{/items}}
有一些方法可以执行此操作..??
【问题讨论】:
标签: 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 法国
【讨论】:
在迭代中使用 {{@index}}。
{{#data}}
<p>Index is {{@index}}</p>
{{/data}}
【讨论】:
Mustache,此方法不起作用。我相信这要么一直是 Handlebar 的专有功能,要么已经从纯粹的 Mustache 中删除至少五年了。
您可以使用车把扩展来留胡子并编写一个辅助函数来碰撞计数器。
我在这里做了更多的解释。 In Mustache, How to get the index of the current Section
【讨论】:
或者,只需在您的数组中添加一个计数器...我知道这是一个丑陋的解决方案,但它是最易读的并且可以完成工作。
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}}
【讨论】: