Home > front end >  Dynamically set a number in a classname depending on the number of elements in a loop
Dynamically set a number in a classname depending on the number of elements in a loop

Time:10-22

The thing is a little bit difficult to explain for me, so I'll do my best. I have a slider, and inside it a each loop returns 3 elements (three products), and I want to set a classname "slider-n" where n is the element number (it should be 1, 2 and 3). I can't, for example, put "product.id" because the products will change and the id's too (actually, the ids are 14, 15, and 16) so I've been wondering what's the best solution for this. There's a photo of the structure HERE. Thank you in advance.

CodePudding user response:

You can use each.with_index :

<% @store_preview.each.with_index do |product, index| %>
  <div class="slide-<%= index %>"
    ...
  </div>
<% end %>
  • Related