5

How do I assign page-specific CSS classes to the tags that are used in common layout?

I have an application.html.erb layout file, which loads application.css.scss <%= stylesheet_link_tag "application". . . %>, which, in its turn, uses all CSS files in directory (there's one custom.css.scss in my case).

I have four static pages and one layout. I want the Home page to be slightly different from the others: add a class to body for full-page background, make navigation of different colors, etc.

So what's my application.html.erb layout is looks like:

<DOCTYPE! html>
<html>
  <head>
    ·
    ·
  </head>
  <body>
    <header>
      ·
      ·
    </header>
    ·
    <%= yield %>
    ·
  </body>
</html>

And my home.html.erb:

<div>
  Content unique for this page
</div>

So I want to assign some classes to the <body> and <header> tags, but only on the Home page.

What's the best way to do this?

(I was thinking of creating an individual layout for Home page (and then an individual CSS for Home page, etc.. But I believe there's got to be another, better way).

3
  • Your home page, to which controller and action it belongs? Commented Nov 25, 2014 at 7:55
  • Check #{params[:controller]} and accordingly add class to body Commented Nov 25, 2014 at 7:58
  • @Vucko, it belongs to StaticPagesController and home action. Commented Nov 25, 2014 at 8:06

1 Answer 1

10

I think content_for will be good for this.

In your layout application.html.erb:

<DOCTYPE! html>
<html>
  <head>
    ·
    ·
  </head>
  <body class="<%= content_for :body_class %>">
    <header class="<%= content_for :header_class %>">
      ·
      ·
    </header>
    ·
    <%= yield %>
    ·
  </body>
</html>

In view home.html.erb:

<% content_for :body_class, 'class1' %>
<% content_for :header_class, 'class2' %>

<div>
  Content unique for this page
</div>

Its much more flexible and easier than use conditionals and check current controller with action.

http://guides.rubyonrails.org/layouts_and_rendering.html#using-the-content-for-method

Sign up to request clarification or add additional context in comments.

1 Comment

Love the simplicity of solution. This is exactly what I was looking for. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.