Use Variable Defined in Config.Rb in SCSS Files

Use variable defined in config.rb in scss files

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.

How to configure a SCSS project?

Both Sass and Compass provide watch commands. You can use either:

sass --watch input.scss:output.css (options)

or, assuming you've got your Compass config file correctly setting your css_dir vairable:

compass watch

Either of those should recompile the css file upon changes. If you want this done live on the server, you'll need to execute the watch command on the server.

Provide sass variables definitions on command-line

The facility I needed is simply not in SASS. Even if you could define variables on the command-line the "if" facility is insufficient to actually do conditional blocks in the style sheet.

Instead I've resorted to the old stand-by of M4. I simply preprocess the SASS with M4, doing command-line options and full conditional blocks.



Related Topics



Leave a reply



Submit