Search code examples
ember.jshandlebars.js

How to set active class in first item of loop?


I am using:

DEBUG: -------------------------------
DEBUG: Ember             : 2.2.0
DEBUG: Ember Data        : 2.2.1
DEBUG: jQuery            : 1.11.3
DEBUG: Ember Simple Auth : 1.0.0
DEBUG: -------------------------------

Although Ember is using Handlebars, and Handlebars has built in support for loop operators, there is not support for @index, @first, @last in Ember (no idea how this feature has been lost)

(the syntax for each loops has changed several times, so I am maybe using outdated examples here)

I am unable to code this:

  {{#each model.images as |image| }}
  <div class="item {{if @first "active" }}" data-slide-number="{{@index}}">
    <img src="{{image.image}}">
  </div>
  {{/each}}

Which is using:

A way of accessing the index has been hacked into ember some time ago, so that I can now do:

  {{#each model.images as |image index| }}
  <div class="item {{if @first "active" }}" data-slide-number="{{index}}">
    <img src="{{image.image}}">
  </div>
  {{/each}}

But that only affects the @index replacement. I am unable to find anything about @first or @last. I could hack it by using a helper, but that probably does not work anymore with the current ember version, and if it does, it will surely break in a couple of weeks. And anyway has probably some rough edges which make it unusable.

Or I could create a controller for my collection so that I can do all kind of strange things just to get the .first or .last property. But that really seems too much work just to get such a simple feature.

Other frameworks are supporting this simple feature out of the box. Am I unable to find it, or is it really not supported by Ember?


Solution

  • You can use ember-truth-helpers to create correct template logic.

    {{#each model.images as |image index| }}
      <div class="item {{if (eq index 0) "active" }}" data-slide-number="{{index}}">
        <img src="{{image.image}}">
      </div>
    {{/each}}
    

    For more information see my other answer about how to recreate @index, @key and @first Handlebars expressions.