Integrate Twitter Bootstrap 4 with Rails 5.2

Time: 10 minutes

Add bootstrap gem to Gemfile.

gem 'bootstrap', '~> 4.2.1'

Install the bootstrap gem.


This throws errors:

Bundler could not find compatible versions for gem "ffi":
  In snapshot (Gemfile.lock):
    ffi (= 1.10.0)

  In Gemfile:
    selenium-webdriver was resolved to 3.141.0, which depends on
      childprocess (~> 0.5) was resolved to 0.9.0, which depends on
        ffi (~> 1.0, >= 1.0.11)

    listen (>= 3.0.5, < 3.2) was resolved to 3.1.5, which depends on
      rb-inotify (~> 0.9, >= 0.9.7) was resolved to 0.10.0, which depends on
        ffi (~> 1.0)

    bootstrap (~> 4.2.1) was resolved to 4.2.1, which depends on
      sassc-rails (>= 2.0.0) was resolved to 2.1.0, which depends on
        sassc (>= 2.0) was resolved to 2.0.0, which depends on
          ffi (~> 1.9.6)

Running `bundle update` will rebuild your snapshot from scratch, using only
the gems in your Gemfile, which may resolve the conflict.


bundle update

Ensure that sprockets-rails is at least v2.3.2.

gem list sprockets-rails

*** LOCAL GEMS ***

sprockets-rails (3.2.1)

Rename application.css to application.scss. Import bootstrap in application.scss.

/* Custom bootstrap variables must be set or imported *before* bootstrap. */

@import "bootstrap";

Remove the lines:

 *= require_tree .
 *= require_self

from application.scss.

Add jquery to Gemfile:

gem 'jquery-rails'

Run bundle. This will install jquery-rails 4.3.3. Add bootstrap dependencies in application.js:

//= require jquery3
//= require popper
//= require bootstrap

So it now looks like this:

//= require jquery3
//= require popper
//= require bootstrap  
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require_tree .

Add a navigation bar to the application layout.

<nav class="navbar navbar-expand-lg navbar-light bg-light" style="background-color: #71da71;">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>

Enclose the main content within a container in the application layout:

<div class='container'>
  <%= yield %>  

You can now see the navigation bar styled using Twitter Bootstrap 4. See it in action at DeveloperTask.

Related Articles