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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With