views:

58

answers:

1

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?

+5  A: 

I use the first way, but with a slightly more succinct syntax:

<div class="<%= 'ok' if @status == 'success' %>">

Though usually you should represent success with boolean true or a numeric record ID, and failure with boolean false or nil. This way you can just test your variable:

<div class="<%= 'ok' if @success %>">

A second form using the ternary ?: operator is useful if you want to choose between two classes:

<div class="<%= @success ? 'good' : 'bad' %>">

Finally, you can use Rail's record tag helpers such as div_for, which will automagically set your ID and class based on the record you give it. Given a Person with id 47:

# <div id="person_47" class="person good">
<% div_for @person, :class => (@success ? 'good' : 'bad') do %>
<% end %>
meagar
+1 tag helpers seems to be a clean approach
Anurag
@meager, I did not know about `div_for`. Very cool :)
macek
@Anurag, check this out http://api.rubyonrails.org/classes/ActionController/RecordIdentifier.html#M000482. Pretty neat stuff.
macek
thanks for the link @macek. this is very similar to how I create elements on MooTools :) neat and tidy
Anurag