Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails each method with changing html (bootstrap carousel)

So, I'm trying to figure out a solution for Bootstrap 3's carousel in Rails 4.

I've got this:

  <li> <a id="carousel-selector-0" class="selected">
    <%= image_tag @gallery.images[0].photo.url(:thumb), class: 'img-responsive' %>
  </a></li>
  <li> <a id="carousel-selector-1">
    <%= image_tag @gallery.images[1].photo.url(:thumb), class: 'img-responsive' %>
  </a></li> 


 ...etc...

I'm looking for an each type method that would account for a variable number of images in a gallery.

Something where the first photo looks like this:

  <li> <a id="carousel-selector-0" class="selected">
    <%= image_tag @gallery.images[0].photo.url(:thumb), class: 'img-responsive' %>
  </a></li>

And those after it look like:

<li> <a id="carousel-selector-1">
    <%= image_tag @gallery.images[1].photo.url(:thumb), class: 'img-responsive' %>
  </a></li> 
.......

With each number increasing by one for each photo of course.

Thanks for the help!

SOLUTION

Thank you kindly creativereason!

Heres what worked:

<% @gallery.images.each_with_index do |image, index| %>
  <li> <a id="carousel-selector-<%=index%>" class="<%= 'selected' if index == 0%>">
    <%= image_tag image.photo.url(:thumb), class: 'img-responsive' %>
  </a></li>
  <% end%>

And if anyone is searching for a solution for .carousel-inner div (pretty much the same):

<div class="carousel-inner">
            <% @gallery.images.each_with_index do |image, index| %>
                <div class="item <%= 'active' if index == 0%>" data-slide-number="<%= index %>">
                  <%= image_tag image.photo.url(:large), class: 'img-responsive' %>
                </div>
            <% end%>
            </div>
like image 221
Chris Brown Avatar asked Nov 01 '25 02:11

Chris Brown


1 Answers

Something like this should work:

<% @gallery.images.each_with_index do |image, index| %>
  <li> <a id="carousel-selector-<%=index%>" class="<%='selected' if index == 0%>">
    <%= image_tag image.photo.url(:thumb), class: 'img-responsive' %>
  </a></li>
  <% end%>

Revised: because I didn't notice the selected difference in the li tag. Now I'm using each_with_index

like image 103
creativereason Avatar answered Nov 03 '25 16:11

creativereason