damian004
damian004

Reputation: 268

Using SASS variables in Rails code

I am afraid that this question is simply stupid, but... is there any option to use SASS variables in rails .erb files?

I defined a few colors in my variables.css.scss and I wish to use their values in my views or helpers in Rails. Maybe Rails can see some compiled sass resources or something?

Thank you for answers!

Upvotes: 2

Views: 1551

Answers (1)

Baldrick
Baldrick

Reputation: 24340

You can do it the other way around, ie using ruby code in your css/sccs code. It's a bit tricky, but it may help you :

First declare the color as a ruby constant :

# Put this into config/initializers/constants.rb for example
module Constants
  FOO_COLOR = '#123456'
end 

Next, rename the variables.css.scss into variables.css.scss.erb and use the constant created at the previous step

$fooColor: <%= Constants::FOO_COLOR %>

Finally use the color in your other scss files

@import "_variables";
#foo {
    background-color: $fooColor;
}

And you can also use the Constants::FOO_COLOR in your Rails code too.

Be careful, you may be using precompiled assets in production. It will work with a constant as shown below, but it won't work if you want to change the value, or get it from a DB.

Upvotes: 3

Related Questions