0

I'm having problem accessing the index returned by Collection.find(). In HTML, I'm creating a carousel and I want to make the images dynamic. Before making it dynamic, here's what it looks like:

<div class="carousel-inner">
  <div class="item active">
    <img src="img/homepage/sliders/1.jpg">
  </div>
  <div class="item">
    <img src="img/homepage/sliders/2.jpg">
  </div>
</div>

After implementation, here's the new code:

<div class="carousel-inner">
  {{#each sliders}}              
     <div class="item active">
       <img src="{{this.url}}">
     </div>
  {{/each}}
</div>

Here's what my JS looks like:

Template.homepageSlider.helpers({
    sliders: function() {
        return HomepageSliders.find({}, {fields: {url:1}}).fetch();
    }
});

This sort of works fine, but I wanted to add the class 'active' only on first index. How should I do this?

Thanks a lot!

user3545006
  • 127
  • 2
  • 9

1 Answers1

0

Something like this should work.

JS:

Template.homepageSlider.helpers({
    sliders: function() {
        return _.map(HomepageSliders.find({}, {fields: {url:1}}).fetch(),
                     function(val, index) { 
                          return {value: val, 
                                  class: (index == 0 ? "item active" : "item")} 
                     });
    }
});

HTML:

<div class="carousel-inner">
  {{#each sliders}}              
     <div class="{{this.class}}">
       <img src="{{this.value.url}}">
     </div>
  {{/each}}
</div>
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
  • Thanks, Christian! But the solution does not work. Images were stacked up. I've checked the inspect element and looks like the class didn't append on the div. – user3545006 May 21 '15 at 07:19
  • that's probably because he called the attribute "active" in one function and then accessed it as "class" in the helper. – illuminaut May 21 '15 at 07:22
  • It now works! Just change the '{{this.class}}' to '{{this.active}}'. Thanks again! :) – user3545006 May 21 '15 at 07:29