Access Rails Controller instance variables in CSS

So, I saw a lot of discussion about SO about using erb in your CSS files. I can get ERB to process CSS files using the syntax <% =%> and adding the .erb file to the file, but I really need to access the instance variables in the controller.

searches_controller.rb

def new @search = Search.new @school = School.find(params[:school]) end 

I would like:

searches.css.scss.erb

 h1.logo { color: <%= @school.primary_color %>; } 

but ERB throws an error because @school is null. Is there a way to require the controller to access these instance variables?

The only way I can do this is to insert it as an attribute of the data in the views, and then use JS to change it on the front side. This seems to me potentially better since the CSS file will not change, and it needs to be repeated every time, but it will also be much less elegant.

+6
source share
2 answers

You also need to keep in mind that in a scenario with a precompiled asset, CSS will run through Sprockets at compile time, so you get a static color (assuming that @school actually created, which won't happen). This is undesirable, since each school will have the same color (regardless of what happened at the compilation stage).

For a custom corporate identity, we allow our users to specify their colors and include the layout block in the block:

 :css h1.logo { color: <%= @school.primary_color %>; } 

This is not ideal, but if you have a small number of settings, it seems to work quite well.

+9
source

I would rather use @school.primary_color in your view. This should work:

 <h1 style="color:#{@school.primary_color}">@school.name</h1> 

Remember to use double quotes for interpolation.

+2
source

All Articles