Assigning a body class to your page layout in Ruby on Rails
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 is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.
Contact
my name at gmail.com
More snippets
Take a look in the archive
Need a website?
Contact my employer. Make sure to check out our portfolio of work.
Hosting
I recommend hostingrails.com
4 comments made
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
Well, that didn’t work—looks like block-code isn’t supported by textpattern. Let me try it again:
Why not move the
into a helper function?
def body_class return (@body_class.nil?) ? ”” : ” class=’#{@body_class}’” end
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.
Usefull post!
Got something to say?