Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Less in a Ruby on Rails 3.1 application?

What is the easiest (is there an easy way?) to use Less (in combination with Sass/Scss) in the Ruby on Rails 3.1 assets pipeline?

I want to load a file like foo.css.less like I would do for bar.css.scss

I found some wonky solution that does not work for me (haven't tried a lot): https://github.com/thisduck/ruby-less-js/issues/2

The idea would be to use Twitter Bootstrap in a clean way.

like image 735
Sucrenoir Avatar asked Sep 06 '11 13:09

Sucrenoir


1 Answers

If you only want to use Bootstrap, you can do it by including the 'less-rails' and 'less-rails-bootstrap' gems in your Gem file.

Then, you can @import bootstrap in your .css.less files:

@import "twitter/bootstrap"

Alternatively, you can include each constituent file individually (excluding those you don't want):

// Reset
@import "twitter/bootstrap/reset";

// Core variables and mixins
@import "twitter/bootstrap/variables";

@import "twitter/bootstrap/mixins";

// Grid system and page structure
@import "twitter/bootstrap/scaffolding";

// Styled patterns and elements
@import "twitter/bootstrap/type";
@import "twitter/bootstrap/forms";
@import "twitter/bootstrap/tables";
@import "twitter/bootstrap/patterns";

If you don't want to use the less-rails-bootstrap gem for whatever reason, or you have non-bootstrap .less files that you want to include, you need to manually add your .less paths to the less-rails config.

Note that none of this extra work is necessary if your filenames end in .css.less as the asset-pipeline should handle that compilation for you (as long as you've included 'less-rails'). This procedure is only required if you want to refer to external .less files directly in your app's .css.less files.

The setup I use for bootstrap is to copy the *.less files to vendor/assets/frameworks/twitter/bootstrap. Keeping the files in vendor/assets/stylesheets/... caused me some issues, probably due to Ruby on Rails magic resolving my imports to the unprocessed .less files and not knowing what to do with them (this is only speculation on my part, I didn't look into it fully).

Once you've got the .less files in your project, you need to tell less-rails where to find them. Do that by putting the following in your application.rb.

YourApp::Application.configure do
  config.less.paths << File.join(Rails.root,'vendor','frameworks')
  # Should be set to true in production.
  config.less.compress = false
end

You can them import them in .css.less files by using:

@import "twitter/bootstrap/reset"
@import "twitter/bootstrap/variables"
...
like image 89
billmag Avatar answered Oct 24 '22 15:10

billmag