Ramandeep Singh
Ramandeep Singh

Reputation: 5253

How to import file dynamically in Rails SASS?

Is this possible to load a SASS file dynamically?

Suppose i declare a Global Constant in Rails Initializer BRAND. What i want is, to import a SASS file with the name specified in the constant BRAND.

I want something like @import BRAND in "application.sass". Please tell me how is it possible. Thanx.

Upvotes: 1

Views: 920

Answers (2)

Patrick Oscity
Patrick Oscity

Reputation: 54684

You can use multiple preprocessors with the asset pipeline, thus using ERB before the SASS processor comes into play. In order to do this, just append .erb to the filename of the file that you want to be preprocessed. For example:

config/initializers/brand.rb:

BRAND = 'mybrand'

app/assets/stylesheets/_mybrand.css.scss:

$brand-color: steelblue;

app/assets/stylesheets/main.css.scss.erb:

@import '<%= BRAND %>';

body {
  background: $brand-color;
}

Edit

By the way, you should not use Sprockets' require directives when working with SASS, as suggested by the Rails Guide on the Asset Pipeline:

If you want to use multiple Sass files, you should generally use the Sass @import rule instead of these Sprockets directives. Using Sprockets directives all Sass files exist within their own scope, making variables or mixins only available within the document they were defined in.

Upvotes: 1

froderik
froderik

Reputation: 4808

You can do it in your (haml) layout file like this:

= stylesheet_link_tag BRAND, :media => 'all'

(or with the extra <% %> if you are using ERB).

Upvotes: 0

Related Questions