How do I make my LESS variables available for all CSS files in Rails?

asset-pipeline, less, ruby-on-rails-3, twitter-bootstrap

Solution

You don't need to use ERB for asset path helpers – they're actually baked into the less-rails gem, which you can reference here: https://github.com/metaskills/less-rails/#helpers

You should be able to just use asset-path or asset-url anywhere you've used ERB to refer to the assets pipeline.

Given this, the best way to go would be to:

- Convert `application.css` to `application.css.less`

- Delete all the Sprockets directives

- `@import` each individual file in the directory.

- Remove the .erb extension from any files that have it, and change ERB asset helpers to less-rails asset helpers.

- Make sure `annotations.css.less` is imported after `bootstrap_and_overrides` – this is why it's usually not a good idea to use `require_tree .`, since you can't control the order in which the files are loaded. The way you have it now, annotations.css.less would be loaded before bootstrap_and_overrides – before the variable you want to use even exists.

Hope that helps!

Problem

What I have: In Rails 3.2.2, I have the following stylesheets: ``` app/assets/stylesheets | |-- application.css |-- bootstrap_and_overrides.css.less | |-- annotations.css.less |-- maps.css.less.erb `-- users.css.less.erb ``` The two first ones are more or less system-default. The other ones are where I define my custom styles. So, `application.css`, as usual, includes all the other files: ``` *= require_self *= require_tree . ``` And `bootstrap_and_overrides.css.less`, of course, includes Twitter Bootstrap as well as some other custom defined LESS variables. ``` @import "twitter/bootstrap/bootstrap"; @import "twitter/bootstrap/responsive"; // other stuff @brown_text: #332820; ``` What doesn't work: Now, in `annotations.css.less`, I'd like to use `@brown_text`, but it gives me: `variable @brown_text is undefined` I figure this is because there's no reference from `annotations.css.less` to the "master" file where the variable would be defined. And it seems that `annotations.css.less` is compiled first – note that I'm currently in development environment. So, how can I use my custom LESS variables then, and make them available in other stylesheet files? My current "fix" is to just move all my custom styles into `bootstrap_and_overrides.css.less.erb`, which doesn't seem very clean at all. What also doesn't work: Just `import`ing the LESS files isn't possible, because they use Rails' asset path helpers. And importing an ERB file is also not possible, since the `@import` statement won't find the file, because it expects a `.less` suffix.

Original source