user1919937
user1919937

Reputation: 447

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?

Upvotes: 12

Views: 11901

Answers (6)

user427390
user427390

Reputation:

I prefer to use the following method:

<body class="<%= content_for?(:body_class) ? yield(:body_class) : controller_name %>">

That method avoids the dreaded <body class>.

I frequently use the controller name to scope a number of styles so it's nice to not need to supply a content_for on every view if I only needed that one class.

Upvotes: 1

Greg Blass
Greg Blass

Reputation: 3650

I've used the accepted method in my app for a while, but never really loved how it worked, because if there is no class, you're gonna have that class=' ' on your body tag, littering your code. For my current use case, I just wanted a widescreen class (but you could easily get more advanced with different classes per your use case). I'm happy with this approach:

In your application helper:

def body_tag(&block)
  content = capture(&block)
  content_tag(:body, content, class: @widescreen ? "widescreen" : nil)
end

In application.html.erb

<%= body_tag do %>
  <%# the rest of your content here %>
<% end %>

Then in your application controller:

private
  def enable_widescreen
    @widescreen = true
  end

Then in any controller that you want it, just do:

before_action :enable_widescreen

Then feel free to make the class logic more advanced if you want to use it for different classes besides 'widescreen' - but the point is that this is an elegant way to allow for there NOT to be a class if you don't specify one, without

<body class>

showing up in your html.

Upvotes: 0

Paul W
Paul W

Reputation: 226

In the layout page:

<% if content_for?(:body_class) %>
  <body class="<%= content_for(:body_class) %>" >
<% else %>
 <body>
<% end %>

In the content page:

<% content_for :body_class do  'my-body-class' end %>

Upvotes: 1

johnrbnz
johnrbnz

Reputation: 387

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

Upvotes: 5

Kyle Macey
Kyle Macey

Reputation: 8154

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) %>">

Upvotes: 5

Jiř&#237; Posp&#237;šil
Jiř&#237; Posp&#237;šil

Reputation: 14401

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) %>">

Upvotes: 44

Related Questions