Вопрос

I am working on a Rails 3.1 app and need a solution for dynamically compiling css. In my app I am allowing users to set the colors and would like to conditionally use „live compilation" on the one SCSS file that controls all of the colors, all of my other SCSS files still need to be precompiled. After some searching I am stumped on how to procede. Any suggestions would be helpful.

Thanks in advance fou all of your ideas.

Devin

p.s. - I should also mention that I need to use instance variable in the SCSS also.

Это было полезно?

Решение

You can preprocess your Sass file with ERb. That would allow you to use instance variables set in the controller or view within the .scss file. The file itself could just be treated as normal view, rendered by a controller as part of an action.

This code is untested, but it should give you a place to start. It assumes you store the user's color preferences as part of the User model itself.

First define your custom action on the UsersController:

# config/routes.rb
match '/users/:id/styles' => 'users#styles', :as => :user_styles

Link to the "stylesheet" in your layout:

# app/views/layouts/application.html.erb
= stylesheet_link_tag 'application', user_styles_path(current_user, :format => 'css')

Define the action in your controller. You could do whatever you want to retrieve the user's preferences here:

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def styles
    @colors = User.find(params[:id]).colors
  end
end

That action will automatically render this view:

# app/views/users/styles.css.scss.erb
$background-color: <%= @colors[:background] %>;

body {
  background-color: $background-color;
}

Adapt as needed.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top