In your controller create a private method thus:
private
def add_body_class(new_class)
@body_class ||= ""
@body_class << " #{new_class}"
end
Then in your controller actions you can add a body class with:
add_body_class "two_col"
The reason for the add_body_class method is so that you can easily add multiple classes without worrying if you have already set the body_class instance variable.
I find this useful because quite often I will use a before filter to set a generic body class for every action in the controller...
before_filter :set_body_class
private
def set_body_class
add_body_class "some_section_name"
end
To output @body_class replace your layout body tag with this:
<body<%= (@body_class.nil?) ? "" : " class='#{@body_class}'" %>>
That's basically a one line if statement that checks if @body_class exists before setting the class on the body tag.
About Paul
Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.
Follow Paul on Twitter
Email: paulsturgess [at] gmail.com
Comments...
Why not move the
bc. <%= (@body_class.nil?) ? "" : " class='#{@body_class}'" %>
into a helper function?
bc. def body_class
return (@body_class.nil?) ? "" : " class='#{@body_class}'"
end
dstar at 01 May 08 at 09:05
Well, that didn't work -- looks like block-code isn't supported by textpattern. Let me try it again:
Why not move the
<= (@body_class.nil?) ? â€â€ : †class=’#{@body_class}’†>
into a helper function?
def body_class
return (@body_class.nil?) ? â€â€ : †class=’#{@body_class}’â€
end
dstar at 01 May 08 at 09:08
It's a fair point.
If I was re-using it in multiple places (templates) I'd put it in a helper.
For the purposes of keeping the tutorial simple I didn't.
Paul Sturgess at 01 May 08 at 09:24
Usefull post!
Mark at 03 May 08 at 07:59
Good post but I'll reiterate what dstar said: this should be in a helper. Unless, of course, your website is only 1 page, or you only require this functionality on-demand.
This return would be more helpful:
return (@body_class.nil?) ? " class='"#{[controller_name, action_name].join('-')}" : " class='#{@body_class}'"
Damien at 16 Dec 11 at 15:54
Got something to say?