4

In Django there is a template tag called cycle: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#cycle

An example:

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

Output:

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

How do you implement this type of functionality in Handlebars.js?

mie.ppa
  • 125
  • 3
  • 10
hekevintran
  • 22,822
  • 32
  • 111
  • 180

2 Answers2

3

I found at 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}}
hekevintran
  • 22,822
  • 32
  • 111
  • 180
2

Here is what I came up with:

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}} 
JoN1oP
  • 21
  • 1
  • I had to remove the `+ 1` from the `(values.length + 1)`, to make it work correctly. It was selecting one empty string as the value at the end of the array. – daangemist Feb 07 '17 at 14:35