Search code examples
handlebars.jsmandrill

mandrill handlebars each loop - how to check odd items


I'm using mandrillapp to send massive-customized email using send-api. My template is using handlebar syntax recently supported by mandrill: https://mandrill.zendesk.com/hc/en-us/articles/205582537 and the #each loop I'm using seems to work well.

Now I need to iterate little bit better: i.e. looking if the item in the each loop is odd or even, if is the last or something like that.

<div class="entry">
  {{#each products}}
    <div class="odd"> <!-- how to change class to even?-->
      <div>{{name}}</div>
      <div>{{price}}€</div>
    </div>
  {{/each}}
</div>

Note: I'm not talking about "handlebarsjs" but only about the handlebar syntax available in mandrill templates


Solution

  • You can't check that with something {{#like @index % 2}} But if you have a list with properties, you can add the property "odd" to your list to check, so your list will look something like this:

    products: [
        {'name': 'productName1', 'price': 22, 'odd': true},
        {'name': 'productName1', 'price': 22, 'odd': false},
        {'name': 'productName2', 'price': 13, 'odd': true},
        {'name': 'productName3', 'price': 42, 'odd': false},
        {'name': 'productName4', 'price': 63, 'odd': true},
    ]
    

    And your mandrill template should look something like:

    <div class="entry">
      {{#each products}}
        <div class="{{#if odd}}odd{{else}}even{{/if}}"> <!-- how to change class to even-->
          <div>{{name}}</div>
          <div>{{price}}€</div>
        </div>
      {{/each}}
    </div>