Frage

So I've seen lots of discussion on SO about using erb in your CSS files. I can get ERB to process the CSS files by using the <%= %> syntax and adding .erb to the file, but what I really need is to access instance variables in the controller.

searches_controller.rb

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

What I would really like to do is:

searches.css.scss.erb

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

but ERB will throw an error because @school is nil. Is there some way to require the controller to access those instance variables?

The only other way I can think to do it is to embed it as an data-attribute in the views and then use JS to change it on the front end. This strikes me as potentially better since the CSS file won't change and need to be resent every time, but it would also be a lot less elegant.

War es hilfreich?

Lösung

You also need to consider that in a pre-compiled asset scenario, the CSS will be run through Sprockets during compilation, so you'd end up with a static colour (assuming @school was actually instantiated which it wouldn't be). This is undesirable as every school would then have the same colour (whatever that happened to be during compilation stage).

For custom branding like this we let our users specify their colours, and include a block of CSS in the layout:

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

It isn't ideal, but if you have a small number of customisations seems to work fairly well.

Andere Tipps

I'd rather use the @school.primary_color in your view. This should work:

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

Just remember to use double quotation marks for interpolation.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top