4

在 Django 中有一个名为循环的模板标签: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 中实现这种类型的功能?

4

2 回答 2

3

我在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}}
于 2012-03-10T14:20:07.577 回答
2

这是我想出的:

Handlebars.registerHelper('cycle', function(value, block) {
  var values = value.split(' ');
  return values[block.data.index % (values.length + 1)];
});

{{#each users}}
  <tr class="{{cycle 'alternate'}}">
  <tr class="{{cycle 'odd even'}}">
{{/each}} 
于 2014-07-02T10:54:06.713 回答