有没有办法在胡子迭代中设置计数器?

Mus*_*wbe 13 mustache

我有一个代码,使用一些迭代渲染胡子模板,如:

{{#items}}
  some html code....
{{/items}}
Run Code Online (Sandbox Code Playgroud)

但我想在迭代中放置渲染项目的数量,如下所示:

{{#items}}
  This is the item [COUNTER-VAR]
{{/items}}
Run Code Online (Sandbox Code Playgroud)

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

mma*_*rin 14

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

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

<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>
Run Code Online (Sandbox Code Playgroud)

...以及以下代码,您可以构建编号列表.

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);
}
Run Code Online (Sandbox Code Playgroud)

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


Dmi*_*hev 6

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

{{#data}}
    <p>Index is {{@index}}</p>
{{/data}}
Run Code Online (Sandbox Code Playgroud)

  • 如果使用纯“Mustache”,此方法不起作用。我相信这要么一直是“Handlebar”独有的功能,要么已经从纯粹的“Mustache”中删除了至少五年。 (3认同)

mat*_*tsh -1

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

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