Cycle Background Colors Of Elements In Rails

Posted By Weston Ganger

I was previously having to add extra lines of HTML to achieve this. Stumbled upon this is the rails docs, gonna really come in handy.


<% @posts.each do %>
  <div style="background-color: <%= cycle("red","green","blue", name: "colors");" %></div>
<% end %>

If you need to use that cycle color or value more than once in the loop it looks like this


<% @posts.each do %>
  <div style="background-color: <%= cycle("red","green","blue", name: "colors");" %>
    <span style="background-color: <%= current_cycle %>">sample text</span>
  </div>
<% end %>

Article Topic:Software Development - Rails

Date:July 04, 2014