0

I am trying to build a bootstrap carousel on my page. The carousel needs to look like this, with the first element having an active class.

  <ol class="carousel-indicators">
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
    <li data-target="#carousel-example-generic" data-slide-to="1"></li>
    <li data-target="#carousel-example-generic" data-slide-to="2"></li>
  </ol> 

How do I achieve the same thing in Ruby? Can I print the data slide number, and the active class from the same statement.

  <ol class="carousel-indicators">
    <% @order_items.each_index do |n| %>
    <li data-target="#carousel-order-item" data-slide-to=<%= "#{n}";  (n == 0) ? "class="active"" : '' %>></li>
    <% end %>   
  </ol>

Thanks!

1
  • you probably should move the logic into an helper method Commented Jan 16, 2014 at 20:57

3 Answers 3

2

Try this and comment back with your results so that I can further assist you.

<% @order_items.each_index do |n| %>
  <li data-target="#carousel-order-item" data-slide-to="<%= n %>" 
  <%= "class=\"active\"" if n == 0 %> ></li>
<% end %>  

This works as such

order_items = %w{ mice rice lice }

order_items.each_index do |n| 
  puts n
  puts "class=\"active\"" if (n == 0)
end 

When n == 0 then class="active" will be output.

Sign up to request clarification or add additional context in comments.

2 Comments

Great, thanks! See my comment to Andrew above, about the double quotes, but other than that, this works.
@learning_to_swim try the code now. I escaped the dbl quotes. The output should be proper. Happy coding :)
1

I think this is what you want

<li data-target="#carousel-order-item" data-slide-to="<%= n.to_s %>" <%= if (n == 0) ? 'class="active"' : '' %> ></li>

1 Comment

Thanks Andrew. The single quotes around the 'class="Active"' is adding double quotes around Active, to make it class=""Active"". So I just have 'class=Active' now and the HTMl appears right. Also, any reason why you have the to_s in there.
1

Well this is just going to be an array so what about just getting the index of each element? Something like-

<ol class="carousel-indicators">
    <% @order_items.each do |n| %>
    <li data-target="#carousel-order-item" data-slide-to="<%= n.index %>" class="<%= 'active'if n.index == 0 %>"></li>
    <% end %>   
  </ol>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.