Using Bootstrap CSS & JS

Using Bootstrap CSS & JS

This article explains how to install and integrate the Bootstrap CSS framework in your Symfony application using Webpack Encore. First, to be able to customize things further, we’ll install bootstrap:

  1. $ yarn add bootstrap --dev

Importing Bootstrap Styles

Now that bootstrap lives in your node_modules/ directory, you can import it from any Sass or JavaScript file. For example, if you already have a global.scss file, import it from there:

  1. // assets/css/global.scss
  2. // customize some Bootstrap variables
  3. $primary: darken(#428bca, 20%);
  4. // the ~ allows you to reference things in node_modules
  5. @import "~bootstrap/scss/bootstrap";

That’s it! This imports the node_modules/bootstrap/scss/bootstrap.scss file into global.scss. You can even customize the Bootstrap variables first!

Tip

If you don’t need all of Bootstrap’s features, you can include specific files in the bootstrap directory instead - e.g. ~bootstrap/scss/alert.

Importing Bootstrap JavaScript

First, install the JavaScript dependencies required by the Bootstrap version used in your application:

  1. // jQuery is only required in versions prior to Bootstrap 5
  2. $ yarn add jquery @popperjs/core --dev

Now, require bootstrap from any of your JavaScript files:

  1. // app.js
  2. const $ = require('jquery');
  3. // this "modifies" the jquery module: adding behavior to it
  4. // the bootstrap module doesn't export/return anything
  5. require('bootstrap');
  6. // or you can include specific pieces
  7. // require('bootstrap/js/dist/tooltip');
  8. // require('bootstrap/js/dist/popover');
  9. $(document).ready(function() {
  10. $('[data-toggle="popover"]').popover();
  11. });

Using other Bootstrap / jQuery Plugins

If you need to use jQuery plugins that work well with jQuery, you may need to use Encore’s autoProvidejQuery() method so that these plugins know where to find jQuery. Then, you can include the needed JavaScript and CSS like normal:

  1. // ...
  2. // require the JavaScript
  3. require('bootstrap-star-rating');
  4. // require 2 CSS files needed
  5. require('bootstrap-star-rating/css/star-rating.css');
  6. require('bootstrap-star-rating/themes/krajee-svg/theme.css');

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.