Rails: Special CSS Class in General Layout

How to set default CSS classes for tags that are used in the general layout?

I have a layout file application.html.erb that loads application.css.scss <%= stylesheet_link_tag "application". . . %> <%= stylesheet_link_tag "application". . . %> <%= stylesheet_link_tag "application". . . %> , which, in turn, uses all the CSS files in (there is one custom.css.scss in my case).

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

So what my application.html.erb layout 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> 

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

What is the best way to do this?

(I was thinking of creating an individual layout for the Home page (and then a separate CSS for the home page, etc. But I believe that there should be a different, better way).

+5
source share
1 answer

I think content_for would be good for this.

In your application.html.erb layout:

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

In the view of 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 lighter than the legend and check of the current controller.

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

+8
source

Source: https://habr.com/ru/post/1207642/


All Articles