Bootstrap in Rails App

Wajeeh Ahsan
2 min readOct 31, 2020

--

Since rails uses the asset pipeline to minify and compress stylesheets, javascripts, and images, using a sass version of bootstrap is the preferred way of including bootstrap over simply including bootstrap in your application layout view. In addition, if you simply included bootstrap in a header file, that included file would have to be a compiled version of bootstrap (it would simply be a css file). However, since we’ll include the sass version of bootstrap in your app, you’ll have access to bootstrap’s sass variables, mixins, and other sass-related awesomeness. You couldn’t get that functionality by including a compiled asset in your application layout view. By importing sass in your application.scss file, rails will compile your bootstrap and assets on the fly and will allow you a lot more flexibility in the design of your apps.

Add this to your Gemfile

'gem 'bootstrap-sass'

And then run

bundle install

Next, you’ll want to import the bootstrap stylesheets in your application css manifest file. However, by default, the manifest file is named:

app/assets/stylesheets/application.css

but you should rename it to use a .scss extension (or .sass extension) like so:

app/assets/stylesheets/application.scss

Now, remove everything in your application.scss file and add the following two lines:

@import "bootstrap-sprockets";
@import "bootstrap";

You’ll need to manually handle the imports of your scss files from now on.

Next, to make bootstrap’s javascript helpers available, you’ll need to add this line:

//= require bootstrap-sprockets

to your `app/assets/javascripts/application.js

You’ll want to add that line is such a way that your application.js file looks like this:

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .

From now to onward, you’ll need to import all css files manually.

Happy coding :)

--

--

Wajeeh Ahsan
Wajeeh Ahsan

No responses yet