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.

Comments left...

  • 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

Got something to say?