Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Class To Body Using ERB In A View - Rails

I've watched this screencast to add a page title when in a view, is there a way I can do the same but add a class the body tag?

like image 202
user1919937 Avatar asked Dec 21 '12 19:12

user1919937


3 Answers

I usually make a helper method for stuff like this so you can have defaults set up cleanly

application_helper.rb
  def body_class(class_name="default_class")
    content_for :body_class, class_name
  end


view:
  <% body_class "foo" %>

application.html.erb
  <body class="<%= yield (:body_class) %>">
like image 31
Kyle Macey Avatar answered Sep 18 '22 16:09

Kyle Macey


Not sure what you mean, you can do it the same way:

In a view:

<% content_for :body_class, "my_class" %>

In a layout file:

<body class="<%= yield (:body_class) %>">
like image 142
Jiří Pospíšil Avatar answered Sep 20 '22 16:09

Jiří Pospíšil


Sometimes using the current controller name as a class name we'll do:

<body class="<%= controller.controller_name %>">

I find this simpler and a bit more elegant, but of course thus you won't be able to assign individual class names.

s. Add Class To Body Using ERB In A View - Rails

like image 20
johnrbnz Avatar answered Sep 20 '22 16:09

johnrbnz