Lee
Lee

Reputation: 95

How to iterate through an array of images using bootstrap carousel

<div class="row">
  <div class="col-md-12">
    <div class="carousel slide" id="myCarousel">
      <% if @room.images[0].medium.url %>
<!-- Indicators -->
        <ol class="carousel-indicators">
          <% @room.images.each do |image| %>
            <li data-target="#myCarousel" data-slide-to="<%= @room.image %>"></li>
              <% end %> 
            </ol>               
          <% end %>     
            <div class="carousel-inner" role="listbox">
              <% if @room.images[0].medium.url %>               
                <% @room.images.each do |image| %>
                  <div class="item <%= 'active' if @room.image == @room.images[0] %>">          
                    <%= image_tag @room.images[0].medium.url %>
                  </div>
                <% end %>   
              <% end %>
            </div>
              <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
                <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
                  <span class="sr-only">Previous</span>
                 </a>
                   <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
                     <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
                      <span class="sr-only">Next</span>
                    </a>
                  </div>
                </div>
              </div>

Trying to get images uploaded by my users to display in bootstrap carousel.

The images are present in my S3 bucket and I can see them in my database, just cant get them to display in the carousel.

If i use <%= image_tag @room.images[0].medium.url %> outside of the carousel it display the first image in the array as expected.

Any suggestions would be appreaciated still trying to find my feet with this.

<script>
$(function(){
  $('#myCarousel').carousel('cycle');
});
</script>

Upvotes: 0

Views: 2069

Answers (1)

Alex K Jose
Alex K Jose

Reputation: 252

There is an error in your .each loop.

Replace the code with the following

first loop

<% @room.images.each do |image| %>
  <li data-target="#myCarousel" data-slide-to="<%= image %>"></li>
<% end %>

second loop

<% @room.images.each do |image| %>
  <div class="item <%= 'active' if image == @room.images[0] %>">          
    <%= image_tag image.medium.url %>
  </div>
<% end %>

I hope this will solve your problem.

Upvotes: 3

Related Questions