How to add bootstrap in rails 7
Bootstrap is a popular CSS framework that can help you quickly design and style your Rails 7 application.
Here are the steps to add Bootstrap to your Rails 7 project:
Add the bootstrap and jquery-rails gems to your Gemfile:
gem 'bootstrap', '~> 5.1'
gem 'jquery-rails', '~> 4.4'
Run bundle install
to install the new gems.
Import the Bootstrap and jQuery CSS and JavaScript files in your application.scss and application.js files, respectively. To do this, add the following lines to your app/assets/stylesheets/application.scss file:
@import "bootstrap";
And add the following line to your app/assets/javascripts/application.js file:
//= require jquery3
//= require popper
//= require bootstrap
Restart your Rails server to ensure that the new assets are loaded.
Verify that Bootstrap is working by adding some sample Bootstrap code to your application layout file.
app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>BootstrapRails7</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-body-tertiary bg-warning">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link disabled">Disabled</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<%= yield %>
</div>
</body>
</html>
This code will create a basic Bootstrap navbar and container for your application.
Restart your Rails server again and visit your application in a web browser. You should see the Bootstrap navbar and container at the top of your page.
Congratulations🎉 , you have now added Bootstrap to your Rails 7 project! You can now use Bootstrap’s classes and components to style your views and make your application look great.
Top comments (0)