13

I'm a newbie to rails, so I wanted to ask how to use bootstrap with rails? before learning back-end development I used to simply call it in the head of the html tag of the html file like this:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

So I was wondering what is the right way to do it in rails? Should I do the same and put these calls in the head of the html tag of the application layout view file (except jQuery because it's already implemented)?

Because if it was that simple, then why did people make special gems for bootstrap?

I'm pretty sure there are many points I'm missing or unaware of, so I would appreciate some clarification and guidance.

PS: The rails app already exists, I just wanna use bootstrap to adjust the design..

1
  • use gem or put source files into vendor/assets
    – KcUS_unico
    Mar 5, 2017 at 14:25

7 Answers 7

14

Why install the bootstrap gem?

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.

Adding Bootstrap to your rails app

According to the bootstrap-sass gem, you need to add

'gem 'bootstrap-sass'

to your Gemfile 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 .
5
  • 1
    There are also arguments in favor of serving your files through CDNs like the op does, I find it much better actually.
    – Eyeslandic
    Mar 4, 2017 at 17:24
  • What is the syntax for manually importing new scss files? Does this happen in the application.scss file, below @import "bootstrap";?
    – sambecker
    Jan 6, 2018 at 19:36
  • Just figured this one out. Was having a problem mixing css into application.scss while trying to import other files. Fixed my issue by creating a global.scss file and then importing it and page.scss and bootstrap into application.scss.
    – sambecker
    Jan 6, 2018 at 19:44
  • @Eyeslandic can you elaborate your reasons why you find it much better to use CDNs rather than the gem? I prefere CDNs also because they might be faster loaded due to the distributed nature and also because they might be already cached if widely used. Or is there anything else im missing?
    – dcts
    Oct 4, 2019 at 12:59
  • Why is this 'better' than including bootstrap at the webpack(er) and package.json level? (Subjective answers are fine.)
    – beporter
    Sep 23, 2021 at 20:38
5

In Bootstrap 4 now you can simply add your @import 'bootstrap'; to your application.scss. You should rename your application.css to application.scss if you have not already.

@import 'bootstrap';

After you have added the gem to your Gem file

...
# Bootstrap
gem 'bootstrap', '~> 4.1.1'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
...

Advantages of using the Sass version is

  1. You can change the default bootstrap variables to your own custom variables
  2. And you can write your own function and mixing without the need to recompile and worry about updates/fix from Bootstrap.
5

1.

rails new bootstrappy

2.

cd bootstrappy

3.

yarn add bootstrap jquery popper.js

4.

in environment.js

config/webpack/environment.js

add the following:

const webpack = require("webpack")

environment.plugins.append("Provide", new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Popper: ['popper.js', 'default']
}))

5.

in application.js

location: app/javascript/packs/application.js add:

import "bootstrap"
import "../stylesheets/application"

document.addEventListener("turbolinks:load", () => {
    $('[data-toggle="tooltip"]').tooltip()
    $('[data-toggle="popover"]').popover()
})

6.

create stylesheets folder in app/javascript

mkdir app/javascript/stylesheets

in stylesheets folder create file: application.scss

7.

in app/javascript/stylesheets/application.scss add :

@import "~bootstrap/scss/bootstrap";

8. update: app/views/layouts/application.html.erb

add:

<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>   

application.html.erb looks like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrappy</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

9. test it out:

add navbar, tooltips, popover to:

app/views/layouts/application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrappy</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 
    'reload' %>
    <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 
    'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>
  <body>   

  <!-- add navbar -->

  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data- 
      target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria- 
      expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
          <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" 
            role="button" 
            data-toggle="  dropdown" aria-haspopup="true" aria-expanded="false">
            Dropdown
          </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" href="#">Action</a>
            <a class="dropdown-item" href="#">Another action</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">Something else here</a>
          </div>
        </li>
        <li class="nav-item">
          <a class="nav-link disabled" href="#" tabindex="-1" aria- 
            disabled="true">Disabled</a>
        </li>
      </ul>
      <form class="form-inline my-2 my-lg-0">
        <input class="form-control mr-sm-2" type="search" placeholder="Search" aria- 
          label="Search">
        <button class="btn btn-outline-success my-2 my-sm-0" 
          type="submit">Search</button>
      </form>
    </div>
  </nav>

  <!-- add tooltips -->

  <button type="button" class="btn btn-secondary" data-toggle="tooltip" data- 
    placement="top" title="Tooltip on top">
    Tooltip on top
  </button>
  <button type="button" class="btn btn-secondary" data-toggle="tooltip" data- 
    placement="right" title="Tooltip on right">
    Tooltip on right
  </button>
  <button type="button" class="btn btn-secondary" data-toggle="tooltip" data- 
    placement="bottom" title="Tooltip on bottom">
    Tooltip on bottom
  </button>
  <button type="button" class="btn btn-secondary" data-toggle="tooltip" data- 
    placement="left" title="Tooltip on left">
    Tooltip on left
  </button>

  <!-- add popover -->

  <button type="button" class="btn btn-lg btn-danger" data-toggle="popover" 
    title="Popover title"   data-content="And here's some amazing content. It's very 
    engaging. Right?">Click to toggle popover</button>
  <%= yield %>
  </body>
</html>

10.

rails g controller main index

11.

update app/config/routes.rb

like this:

Rails.application.routes.draw do
  root to: 'main#index'
end

12.

run start rails server

13. follow this link:

http://localhost:3000/ and enjoy!

3

One major reason for pulling in the bootstrap-sass gem or using the NPM package is so that you can configure, override, and make use of Bootstrap's Sass variables and mixins. When you're pulling in from the CDN you're getting the precompiled and minified CSS, so any styles you want to override have to be done directly on the elements you want to modify, whereas using variables will allow you to consistently modify styling across all bootstrap components by overriding their variables, and you can also use the wide variety of mixins that they have available.

CDN's can be pretty convenient, if you just want to get up and running with the regular bootstrap defaults. The more sites that use the CDN version, the more likely the user will already have that asset downloaded and won't need to request it again for your site.

A couple of other points against CDN's, however:

1) You don't have control over the CDN, so if they have an outage or some sort of bug, you're kind of out of luck. You'll typically want a CDN of some sort fronting your assets one way or another, but it can be nice to have one that you have configuration control over so that you can do things like clear the cache manually or disable for debugging and whatnot.

2) Feature tests will be slower when you're using a CDN as opposed to a gem or NPM package because they also end up having to download the assets. This can also result in flaky tests, something we've especially noticed on CI when using CDN assets.

We switched from the boostrap-sass gem not long ago to the NPM package instead. It works mostly the same as @Mark's description or their instructions, but we had to add the path to the package to our config/initializers/assets.rb file:

# config/initializers/assets.rb
Rails.application.config.assets.paths += [
  # paths for CSS assets in node_modules directory
  Rails.root.join('node_modules', 'bootstrap-sass', 'assets', 'stylesheets')
]
1

In Rails 6 using Webpacker and Yarn as the default options, I installed bootstrap without the gem by basically following this nice writeup. Starting with dependency installation:

yarn add bootstrap jquery popper.js

Added the dependency to my app/javascript/packs/application.js:

require("bootstrap")

I changed app/assets/stylesheets/application.css into a .scss. (The writeup instead uses a custom file for that.) I removed all *= require_ lines and added:

@import "bootstrap/scss/bootstrap";

And that was it. Restarting the server allowed me to add a container and a navbar with a dropdown to my layout.

1

Step 1: Using Yarn:

yarn add bootstrap@4.3.1 jquery popper.js

package.json file should look like this

"dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "bootstrap": "4.3.1",
    "jquery": "^3.4.1",
    "popper.js": "^1.16.1",
    "turbolinks": "^5.2.0"
  },

Step 2: Head to config/webpack/environment.js file and add these lines

const { environment } = require('@rails/webpacker')

const { environment } = require('@rails/webpacker')

const webpack = require("webpack")

environment.plugins.append("Provide", new webpack.ProvidePlugin({

$: 'jquery',

jQuery: 'jquery',

Popper: ['popper.js', 'default']

}))

module.exports = environment

Step 3 : Head to app/assets/stylesheets/application.css and add these lines

*= require bootstrap

*= require_tree .

*= require_self

Congratulation! You have successfully installed Bootstrap 4

copied from https://dev.to/somnathpaul/add-bootstrap-4-to-your-ruby-on-rails-6-application-ole

1
0

Common way to add extensions to the rails app is to include them in the Gemfile

That's where all the libraries live, it is version controlled and in cases like bootstrap, the assets will be handled by the rails asset pipe line

Here is the website for the boostrap gem: https://github.com/twbs/bootstrap-sass

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.