Sample app to add Bootstrap 5, JavaScript and Images to Rails 6.1 App
- ruby 3.0.1p64 (2021-04-05 revision 0fb782ee38) [x86_64-linux]
- Rails 6.1.4
- Bootstrap 5.0.2
- In
application.html.erb
change to stylesheet_pack_tag as shown:
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
- Create new files/folders in
app/javascript
:
app/javascript
└───images
│ test.jpg
│
└───packs
│ application.js # already exists
│ application.scss
│
└───src
│ my_script.js
│
└───stylesheets
my_styles.scss
$ touch packs/application.scss
$ mkdir -p src && touch src/my_script.js
$ mkdir -p stylesheets && touch stylesheets/my_styles.scss
$ mkdir -p images && wget -O images/test.jpg http://lorempixel.com/640/480/
- Add Bootstrap and Popper JS to app
$ yarn add bootstrap
$ yarn add @popperjs/core
- Include Bootstrap in
application.js
file:
require.context("../images", true)
import "bootstrap"
import "@popperjs/core"
import "../src/my_script.js"
Include Bootstrap in application.scss
file:
@import "~bootstrap/scss/bootstrap.scss";
@import "../stylesheets/my_styles.scss"
- Create home controller with index action
$ rails g controller home index
- Add Bootstrap modal component in
app/views/home/index.html.erb
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
- Add Image tag in
app/views/home/index.html.erb
<br>
<%= image_pack_tag("media/images/test.jpg") %>