使用SASS和用户指定的颜色

我正在使用Rails 3构建一个网站,让用户拥有不同布局和配色方案的配置文件。 我已经在使用SASS,如果我可以做这样的事情,变量将是非常宝贵的……

   

…颜色方案定义主要(完全?)SASS变量指定要在布局中使用的颜色。 显然我不能像这样链接SASS或CSS文件,我需要将它们导入SASS。

如何在请求时动态地将SASS文件导入解析器,然后缓存生成的CSS文件以供以后使用?

我已经考虑过在部署中构建所有可能组合的丑陋路线,但如果我想让用户在未来设置自己的颜色,那仍然会让我感到不安。 看起来像SASS这样的低调水果,它可能也可以实施。

好吧,我挖掘了Sass文档,看起来可以使用它们的function,但看起来它过于复杂并且后来无论如何都会引入问题。

我发现这样做的最好方法是在更新设置时生成特定于用户的模板。 无论如何,这样做效果更好,因为在等待解析器时,请求永远不会延迟。

 # unless cached_copy_exists template = %Q{ @import '/path/to/color_scheme'; @import '/path/to/layout'; } output = Sass::Engine.new(template, :syntax => :scss).render # output rendered CSS to file for inclusion in HTML template 

为了允许自定义颜色,用户输入可以组装成字符串中的SASS css变量,并预先附加到传递给Sass解析/呈现引擎的模板文件中。

更新:

根据请求,这里有一个更加充实的示例,说明如何工作,只关注使用Sass变量和预编码的Sass样式表(简化以隔离此特定问题):

 # config/routes.rb resources :stylesheets, only: [:show] # app/controllers/stylesheets_controller.rb class StylesheetsController < ApplicationController layout nil def show styles = Stylesheet.find(params[:id]) base_stylesheet_path = Rails.root.join('app', 'assets', 'profile.scss') # Build the string of SCSS we'll pass to the Sass rendering engine @sass = <<-SASS #{styles.to_sass} @import "#{base_stylesheet_path}"; SASS # Cache for long time response.headers['Cache-Control'] = "public, max-age=#{1.year}" respond_to do |format| format.css end end end # app/views/stylesheets/show.css.erb <%= raw Sass::Engine.new(@sass :syntax => :scss).render -%> # app/models/stylesheet.rb class Stylesheet < ActiveRecord::Base serialize :variables, JSON def to_sass # Convert a hash of variables into SCSS variables.each_pair.map do |name, value| "$#{name}: #{value};" end.join("\n") end end # example for the stylesheet model stylesheet = Stylesheet.new stylesheet.variables[:primary_color] = "#0000ff" stylesheet.save