Exercise: Add an Asset Library for Drupal 8, Drupal 9

Last updated March 2, 2021

You can accomplish a lot without needing to change any markup by adding CSS and JavaScript files to your theme. In this exercise you'll create 2 asset libraries and add them to your theme. Specifically, we want to pull in the CSS and JavaScript from the popular Bootstrap framework so that we can make use of its layout utility classes later on. We'll also add a custom CSS file that contains global styles for our site, like setting the page background color.

If you want to try and complete this on your own first you'll need to:

  • Add the Bootstrap CSS and JavaScript files to your theme.
  • Define an asset library using a THEMENAME.libraries.yml file in your theme.
  • Tell Drupal to attach your asset library so that the CSS and JavaScript files it represents are included in the page.

Once that's done your site won't look all that different. But if you view the page source, or look closely, you should see that the Bootstrap files are included along with any CSS rules you placed into your custom style sheet.

Note: Since this course if focused on teaching the Drupal aspects of theme development, and not on writing CSS, we use the Bootstrap CSS. If you don't need it for your project though you can skip it, or add the CSS framework that you want to use instead.

You should try to complete the exercise steps on your own and use the video to help guide you if you get stuck.

Note: At the end of this exercise, you'll find a video walk-through of the solution.