Adding CSS, Fonts and JavaScript Using Library API in Drupal 8

  • Tech
  • March 21 2018
  • 5 min read

Drupal is one CMS that never ceases to amaze me. Due to the availability of a vast developer community network, Drupal is like an organism that is growing and improving each day.

Launched in 2015, it has built amazing standards in the theming part along with the CSS and JS assets and managing libraries that are called Libraries API. Although it existed earlier even with Drupal 7, in version 8, it comes as the uniform standard way. It uses YAML files to allow you to overwrite core libraries, add libraries to templates, specify dependencies, use third-party libraries.

Assets are no longer automatically loaded unless required. This allows for faster front-end performance. Now, that I have told you about the advantages of using Library API, let's move forward to how important it is to use. In the following section, I will walk you through a step-by-step process on how to create libraries to adding external files. Without wasting time let’s get to it.

Step 1: Creating Libraries

In this step, you will create a *.libraries.yml file. This file will contain all your asset libraries. In case of a theme, you have to create this file in the theme folder. And for a module, you will add this file to the root of the module folder.

Whether you are doing this for a theme or a module, you must replace the " * " in the name of the file with the name of your theme or module.

For example: If your theme is named my_theme, then the name of the YAML file will be my_theme.libraries.yml.

Below is an outline of how you will define a library: 

#Give library a name
    # The SMACSS category
      # Path relative to theme directory
      build/libraries/header/header.css: {}
    # Path relative to theme directory
    build/libraries/header/header.js: {}
    - core/jquery

Make sure that you do not use tabs while making your libraries file. Since it is a YAML file and YAML is very strict in what it allows you to use, you can find a great refresher on YAML right here.

Adding CSS

Also, we see that we have two sections under the name CSS and JS. CSS is a section that contains all the CSS files and all the files are listed under specific categories. For example, in the above example, we have the theme as a category. These are called SMACSS categories and is used by Drupal for CSS files. 

The SMACSS is a method to organize CSS rules and files. There are basically five categories: base, layout, component, state, and theme. You can find more about it here.
We can see that there are curly braces following the path of our file. Here, we can set additional properties.

Adding JS

Similar to CSS, we add all our javascript files in the js section. Although there is no SMACSS category here, in this case, you must know that the JS files are still added in different lines. Also, we can set additional properties in the curly brace, just like we do for CSS.

By default, Drupal 8 adds all the javascript files to the footer of the page, so if you want your JS to be added, you will have to add “header: true” to the library. This will add all your JS and dependencies in the header.

Here, dependencies are any other third party libraries that your library may depend on. They will automatically attach whenever you attach your library and they will load prior to your library.

Adding External Files

You may have to use to use javascript that is externally on a CDN(Content Delivery Network) in some conditions, for example: when you need to add some web fonts to your page. To get these fonts, you will need to use external javascript.

This can be accomplished by providing the URL to retrieve the content and setting the type: external in the library. Even though it is not mandatory, it is a good practice to add some information about the external files in the library.

The following are two examples displaying the addition of font awesome and google font (lato) to the library.

  version: 4.5.0
    name: mit
    gpl-compatible: true
    theme: { type: external, minified: true}
      ‘//’: { external: true}

Now, that you have a basic understanding of the file structure, let’s move on to the next step.

Step 2: Attaching Libraries

Now, there are more than one ways of attaching the libraries. You can attach the libraries by any of the following ways:

  • Through *.info.yml file
  • Through Twig template
  • Through PHP

So. let’s first see how we can attach the libraries using the *.info.yml file.

name: Your Theme
type: theme
description: This is your theme description
core: 8.x
  # The following libraries are added globally
  - your-theme/global

That’s it. That is all that you have to do attach the libraries globally.

As Drupal 8 uses the Twig templating engine, you can attach the libraries directly via Twig templates. For example, if you have a search form block, you can define the css and js for the block, add it to a library, and add that library to the search form block twig template. Those assets specific to the search form block will only be included when the block is rendered. 

{{ attach_library(‘your-theme/search-block’) }}

<div{{ attributes.addClass(classes) }}>
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {% block content %}
    {{ content }}
  {% endblock %}

Apart from the above-mentioned methods, we can also attach libraries using PHP. Using PHP, libraries can be attached in preprocess. It means that you can define a logic that can check for the conditions that need to be met before adding the library to the library array.

  * Implements hook__page_attachments()

Function mytheme_page_attachments(array &$attachments) {
  $attachments[‘#attached’][‘library’][] = ‘your-theme/your-library;

Extend and Override

Among various benefits that come with Drupal 8, this is one of the most useful and important. You can easily extend or override libraries. You can do this using the *.info.yml file. Now, let’s first discuss the library extension.

name: Your Theme
type: theme
description: This is your theme
core: 8.x
  # The following libraries will be added globally

  #Classy’s forums library is only included when the
  # forums.html.twig template is used.

Here, libraries-extend is a property that you will use in your *.info.yml. Here, the extension means that your library will be attached in the same way as a pre-attached library and will extend its functionality.
Now, that you know about libraries-extend, next up is libraries-override.

name: Your Theme
type: theme
description: This is your theme
core: 8.x
  # These libraries will be added globally
  - your-theme-name/global
  # Replace the entire library

  your-base-theme/global: your-child-theme/global
   # Remove the entire library
   your-base-theme/search_form: false

   # Replace a specific file
   # Copy in the library which contains the file you will be replacing
         build/libraries/global/global.css: build/libraries/global/global-new.css
   # remove a specific file
       # original path to the file. not relative to your theme.
         build/libraries/global/global.css: false

Libraries-override is also a property that you will use in the *.info.yml file. It serves as a powerful tool that gives you complete control over the library and allows you to manipulate it in anyway that you see fit.
Using this property, you can replace or remove specific files or even entire libraries. It totally depends on your choice and your needs.

To Sum Up

So, that was all that you needed to get started with using the Libraries API. It is a wonderful tool and can be used to accomplish the tasks quickly. Getting really good at it might take some time but above is the bare minimum that you need to know to start using its power. So, I wish you all the best on your Drupal journey and “May the source be with you”

Become our reader!

Get hand picked blogs directly in your inbox.
The subscriber's email address.