Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable defined in config.rb in scss files

Is it possible to use a variable defined in the config.rb file of a compass project, throughout the SCSS files?

like image 860
alexdmejias Avatar asked Jan 24 '13 16:01

alexdmejias


People also ask

How do I change variables in SCSS?

A Sass variable must be initialized with a value. To change the value, we simply replace the old value with a new one. A variable that's initialized inside a selector can only be used within that selector's scope. A variable that's initialized outside a selector can be used anywhere in the document.

How can we set default value to the variable in Sass?

Description. You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.


1 Answers

In your config.rb file add a custom module:

module Sass::Script::Functions
  def custom_color(value)
    rgb = options[:custom][:custom_colors][value.to_s].scan(/^#?(..?)(..?)(..?)$/).first.map {|a| a.ljust(2, a).to_i(16)}
    Sass::Script::Color.new(rgb)
  end
end

And then set up your variables (again, in the config.rb file):

sass_options = {:custom => { :custom_colors => {"main" => "#ff1122"} } }

Then in your scss file, you can use the custom_color() function:

body {
  background-color: custom_color(main);
}

You could also write another custom function which returns other types such as font sizes, measurements, etc. by passing in strings, and then returning the appropriate class instance.

Interestingly, this would allow you to pass in environment variables into the compass command line, and that would generate different results.

So if you sass_options are:

sass_options = {:custom => { :custom_colors => {"main" => ENV["MAIN_COLOR"]} } }

And you run compass:

MAIN_COLOR=#dd1122 bundle exec compass compile

Then whatever color you pass in on the command line will appear in the resultant css. If you're using Heroku, you could heroku config:set MAIN_COLOR=#224411 and be able to set template colors on a per-app basis, using the same scss files.

like image 108
stef Avatar answered Sep 21 '22 22:09

stef