What's an elegant way to conditionally add a class to an HTML element in a view?
Posted
by ryeguy
on Stack Overflow
See other posts from Stack Overflow
or by ryeguy
Published on 2010-04-13T04:11:51Z
Indexed on
2010/04/13
4:22 UTC
Read the original article
Hit count: 328
ruby-on-rails
|views
I occasionally have to add a class to an html element based on a condition. The problem is I can't figure out a clean way of doing it. Here's an example of the stuff I've tried:
<div <%= if @status = 'success'; "class='ok'"; end %>>
some message here
</div>
OR
<% if @status == 'success' %>
<div class='success'>
<% else %>
<div>
<% end %>
some message here
</div>
I don't like the first approach because it's crowded looking and hard to read. I don't like the second approach because the nesting is screwed up. It'd be nice to put it in the model, (something like @status.css_class
), but that doesn't belong there. What do most people do?
© Stack Overflow or respective owner