gpt4 book ai didi

javascript - 在 Handlebars.js 中实现循环标签

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:37:39 25 4
gpt4 key购买 nike

在 Django 中有一个名为 cycle 的模板标签:https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#cycle

一个例子:

{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}

输出:

<tr class="row1">...</tr>
<tr class="row2">...</tr>
<tr class="row1">...</tr>
<tr class="row2">...</tr>

如何在 Handlebars.js 中实现此类功能?

最佳答案

我在 http://thinkvitamin.com/code/handlebars-js-part-2-partials-and-helpers/ 找到了

Handlebars.registerHelper("stripes", function(array, even, odd, fn) {
if (array && array.length > 0) {
var buffer = "";
for (var i = 0, j = array.length; i < j; i++) {
var item = array[i];

// we'll just put the appropriate stripe class name onto the item for now
item.stripeClass = (i % 2 == 0 ? even : odd);

// show the inside of the block
buffer += fn(item);
}

// return the finished buffer
return buffer;
}
});


{{#stripes myArray "even" "odd"}}
<div class="{{stripeClass}}">
... code for the row ...
</div>
{{/stripes}}

关于javascript - 在 Handlebars.js 中实现循环标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9526008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com