0

My goal is simple, I just want to know the best approach on how to to do this.

Scenario

book_controller

def new
  @book = "book"
end

magazine_controller

def new
  @magazine = "magazine"
end

HTML

application.html.erb

<body>
  <div class="container">
     <body of controller>
  </div>
</body>

books/new.html.erb

<h1>hello book</h1>

magazines/new.html.erb

<h1>hello magazine</h1>

css

.background-black {
    background: black
}

My goal is to add the background-black CSS class to the only book_controller for example

 <div class="container background-black">

But it will affect magazine_controller as well. What if I have 4 controllers that needed the black background and the rest don't need that class. What is the best approach?

airsoftFreak
  • 1,450
  • 5
  • 34
  • 64

2 Answers2

1

The best ways to achieve your goal is to use Controller Specific Assets as recommended in Rails asset pipeline docs ( you can find some implementation details here), but as you said what you want to do is simple so you can simply use erb syntax to dynamically control the value of the class attribute by calling a variable called controller populated by rails and containing information about the controller who render the view like the name of the controller.

<div class="container <%= controller.controller_name == 'book' ? 'background-black' : '' %>">

If you have 4 controllers that needed the black background you can use erb too.

 <div class="container <%= ['book','magazine','user', 'newspaper'].grep(/#{controller.controller_name}/).empty? ? '' : 'background-black' %>">

The answer mentionned here use the same approch but have the advantage of helping you keep your css code clean and readable.
Hope that will help

Bassirou Diaby
  • 279
  • 4
  • 7
0

First, You should delete some codes that //= require_tree in application.css,

Then <% self_css_path = "/assets/"+controller.controller_name %> <%= stylesheet_link_tag self_css_path, :media => "all" %> in application.html.erb

Mick mic
  • 60
  • 9