Last Updated: February 25, 2016
·
2.767K
· mbillard

Automatically add a class to the body tag

Add a class to your body so that you can easily reference it in your CSS to customize specific pages. You can also add a controller method to add additional classes if needed.

In application_helper:

# Outputs the body classes and adds one that
# is automatically generated
# ex: 'admin-users-index-view'
def body_css_class
  @body_css_classes ||= []
  view_css_class = [controller_path.split('/'), action_name, 'view'].flatten.join('-')

  @body_css_classes.unshift(view_css_class).join(' ')
end

Note: You can customize the format easily, remove the 'view' suffix if you don't like it, gsub 'new' and 'edit' for 'form', etc.

In application_controller:

# Controllers can call this to add classes to the body tag
def add_body_css_class(css_class)
  @body_css_classes ||= []
  @body_css_classes << css_class
end

Then in your layout file:

<body class="<%= body_css_class %>">
   ...