How do I get the first item in a collection using Spacebars {{#if}} tags?

I am trying to set the first image as "element active" and the Bootstrap carousel. So, is there a way to make the first item from a collection appear different than the rest?

      {{#each pictures}}
        {{#if @first}}
              <div class="item active">
                 <img src="/pictures/{{fileName}}" alt="" />
            </div>
       {{else}}
          <div class="item">
             <img src="/pictures/{{fileName}}" alt="" />
          </div>
       {{/if}}
     {{/each}}

      

The presented page displays content only in {{else}}. Tried using {{if @first}} but it doesn't work for me.

+3


source to share


2 answers


This is quite similar to a problem requiring an index in your template . You need to match more pictures

and tag the one you need to handle differently. For example:

Template.myPictures.helpers({
  pictures: function() {
    return Pictures.find().map(function(picture, index) {
      if (index === 0)
        picture.isFirst = true;

      return picture;
    });
  }
});

      

Then you can use isFirst

in your template like this:



{{#each pictures}}
  {{#if isFirst}}
    <div class="item active">
      <img src="/pictures/{{fileName}}" alt="" />
    </div>
  {{else}}
    <div class="item">
      <img src="/pictures/{{fileName}}" alt="" />
    </div>
  {{/if}}
{{/each}}

      

Please note that CoffeeScript @

does not work in templates. To learn more about template contexts see this .

+8


source


This is not exactly what you asked, but you can render the first element active

with jQuery in the callback rendered

.



Template.myPictures.rendered = function () {
  this.$('.item').first().addClass('active');
};

      

+2


source







All Articles