Use variable defined in config.rb in scss files

2019-01-17 23:33发布

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

1条回答
孤傲高冷的网名
2楼-- · 2019-01-18 00:16

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.

查看更多
登录 后发表回答