Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: page-specific CSS class in a common layout

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).

like image 991
Nikita Pashinsky Avatar asked Nov 25 '14 07:11

Nikita Pashinsky


1 Answers

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

like image 102
Kirill Platonov Avatar answered Oct 31 '22 07:10

Kirill Platonov