Noz
Noz

Reputation: 6346

Rails Assign Class And Computed Class To HTML Element

This is driving me nuts, I don't see why something so simple is so difficult to do in Rails.

Ok, so I'm looping with an index and attempting to assign individual divs with multiple classes, one is unchanging, but the other gets computed by the loop, i.e., class="item item_1" ... class="item item_2".. and so forth. This is what I have for code thus far:

<% @variable.each_with_index do |item, index| %>
    <div class=<%="item item_#{index}"%>>
           ....
     </div>
<% end %>

But this produces...

<div class="item" item_0="">
....
</div>
<div class="item" item_1="">
....
</div>

How do I go about accomplishing this?

Upvotes: 0

Views: 59

Answers (1)

BaronVonBraun
BaronVonBraun

Reputation: 4293

<div class=<%="item item_#{index}"%>> compiles to <div class=item item_1>, so your browser thinks that the class is item and that item_1 is an attribute.

You just need some quotes around that ERB so it all gets put into the class:

<div class='<%="item item_#{index}"%>'>

should do the trick.

Upvotes: 2

Related Questions