Search code examples
javascriptember.jshandlebars.js

How do you set the class for only the first element in a handlebars foreach loop in emberjs


I am working on an emberjs app which will dynamically create n number of buttons based on my model. To do this, I use a foreach in my template to loop through my model and create a button for each element in the model.

{{#each model.zones as |zone|}}
       <li><a id="{{zone.zone_id}}" {{action 'setData' zone.currenttemp zone.setpoint zone.mode zone.zone_id on='click'}} class="zones">{{zone.zone_name}}: {{zone.currenttemp}}&deg;F</a></li>
{{/each}}

Each button has belongs to the class "zones" but I want only the first button to be a part of the class "active" when the app loads. I understand that the emberjs handlebars does not support the @first operator so I am not sure how to go about this.


Solution

  • each block comes with index variable, and you can combine with if inline helper

    {{#each model.zones as |zone index|}}
           <li><a id="{{zone.zone_id}}" {{action 'setData' zone.currenttemp zone.setpoint zone.mode zone.zone_id on='click'}} class={{if index 'zones' 'active'}}>{{zone.zone_name}}: {{zone.currenttemp}}&deg;F</a></li>
    {{/each}}
    

    If you would like to have some other check then you can install ember-truth-helpers addon.

    class={{if (eq index 0) 'active' 'zones'}}