Body ID's

February 24th, 2007

UPDATE Geoff Grosenbach left a comment of a much more versatile solution than the one used in this post.

Here’s a really quick and simple Rails snip that you can add to your application_helper.rb file.

Say you want to add an id and class to your body element that references the controller and action that you are currently viewing.

1
2
3
  def body_id_class
    "id=\"#{controller.controller_name}\" class=\"#{controller.action_name}\""
  end

Now, in your *.rhtml file you’d do:


  <body <%= body_id_class %>>

controller.controller_name grabs the current controller and calls the controller_name method that will display the currenct controller name. controller.action_name grabs the current controller and calls the action_name method which will display the current action name.

Below is Geoff Grosenbach suggestion for a more versatile solution than the one above.

1
2
3
4
  def body(options={}) 
    options = { :id => controller.controller_name, :class => controller.action_name }.merge(options)   
    tag('body', options, true) 
  end

kain made a nice catch with the tag syntax above – just add true so that the body element is not self closing. The reason?

1
2
3
4
    # File vendor/rails/actionpack/lib/action_view/helpers/tag_helper.rb, line 24
       def tag(name, options = nil, open = false)
         "<#{name}#{tag_options(options) if options}" + (open ? ">" : " />")
       end

I did make one alteration to Geoff’s snip, adding a default set if no parameters are passed to the body method. With Geoff’s code you can then add the following to your *.rhtml file:


  <%= body %>

or something like this:


  <%= body(:style => "width:100%") %>

Thanks Geoff, cool snip!

4 Responses to “Body ID's”

  1. topfunky Says:

    I think that writing a body method that takes a has and applies some defaults would be more versatile.

    def body(options) options = { :id => controller.controller_name, :class => controller.action_name }.merge(options) tag('body', options) end
  2. Robert Says:

    Nice. That would definitely be more versatile. I’ve updated the post to add your snip. Thanks!

  3. kain Says:

    the problem: as far I can see tag(‘body’, options) will generate <body class="index" id="welcome" /> which is invalid (note the close tag)

  4. kain Says:
    
      def body_id_class(options = {})
        options = { :id => controller.controller_name, :class => controller.action_name }.merge(options)
        tag('body', options, true)
      end
    
    

Sorry, comments are closed for this article.