Body ID's
February 24th, 2007
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”
Sorry, comments are closed for this article.


February 26th, 2007 at 11:11 AM
I think that writing a
bodymethod 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) endFebruary 26th, 2007 at 11:42 AM
Nice. That would definitely be more versatile. I’ve updated the post to add your snip. Thanks!
March 10th, 2007 at 01:48 PM
the problem: as far I can see tag(‘body’, options) will generate <body class="index" id="welcome" /> which is invalid (note the close tag)
March 17th, 2007 at 05:33 AM