Skip to content

Assigning a body class to your page layout in Ruby on Rails

Posted on 30 April 2008

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.

View the snippets archive ››

4 comments made

dstar commented on 01 May 08 at 09:05

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 commented on 01 May 08 at 09:08

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

Paul Sturgess commented on 01 May 08 at 09:24

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.

Mark commented on 03 May 08 at 07:59

Usefull post!

Got something to say?

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