Clicky

Drupal 8 - connecting CSS and JS

As you know in Drupal 7, the connection of JS and CSS files has been implemented quite simply, namely using the appropriate functions:

• drupal_add_js () - connection of the JS file
• drupal_add_css () - connection of styles

And there was one more for connecting libraries:

• drupal_add_library ()

In the 8th Drupal version, this approach was abandoned in favor of using libraries. A library in Drupal 8 is a set of JS files and/or style tables, with the necessary dependencies.

By default, Drupal now doesn’t load the necessary JS or CSS files on all pages of the site, unless you explicitly specify it, the reason for this is a poor performance impact. So, if you create a library with your JS file on Jquery, but in the library depending, don`t specify that this library depends on the additional library - Jquery, then Drupal will not automatically connect Jquery.

Now let's start in order. As always, we will test on the custom module. In our case, it will be called library_id.

File library_id.info.yml

 
        name: Library
        
        description: This module demonstrates the use of libraries in Drupal 8
        
        core: 8.x
        
        package: Drupalfly
        
        type: module

        

How to create a library in Drupal 8

To create libraries, use a special file in the format yml, whose name is built from the template:

module_name.libraries.yml

I want to note that all files in the yml format contain only a description of an object, for example module_name.info.yml - contains a description of the module that you can see on the modules page.

In our case, this file will be called library_id.libraries.yml:

File library_id.libraries.yml

 
        library_id:
          version: 1.x
          css:
            base:
              css/library_id.css: {}
          js:
            js/library_id.js: {}
          dependencies:
            - core/jquery
            - core/jquery.once

        

The first line is the name of the library, and then the list of parameters. Each of the parameters starts with a new line, like the values.

CSS - contains a list of files that need to be connected when using this library. As you can see in this parameter, there are additional types, in this case base, this parameter indicates the style type. List of possible types of styles:
  • base - in this type, files with styles that relate to HTML elements, for example a file to reset the normalize styles, must be connected. This type assigns a weight to the CSS_BASE = -200 file;
  • layout - in this type, files whose styles relate to the positioning of elements on the page, for example, the Bootstrap framework files, should be connected. This type assigns a weight to the file CSS_LAYOUT = -100;
  • component - In this type, files whose styles are used repeatedly on the page should be connected. This type assigns a weight to the CSS_COMPONENT = 0 file;
  • state - in this type, files whose styles relate to the change on the client side must be connected. This type assigns a weight to the CSS_STATE = 100 file;
  • theme - In this type, files that use the visual style for the component must be connected. This type assigns to the whole file CSS_THEME = 200.
This approach is defined by SMACSS standards, although we use BEM.
JavaScript(JS) - contains a list of JS files that need to be connected when using this library.
Dependencies - contains a list of libraries that need to be connected when using this library, for example, Jquery.
With the formation of the library finished, now let's figure out how to connect this library? I want to note that in the file module_name.libraries.yml - you can specify any number of libraries.

Connect the library to the page of the site

To connect, use hook_preprocess_page () from our module:

File library_id.module
 
        <? php

        / **
         * @param $ variables
         * Implements hook_preprocess_page ()
         * /
        function library_id_preprocess_page (& $ variables) {

          #Add library
          $ variables ['# attached'] ['library'] [] = 'library_id/library_id';

        }
        

As a JS file in our library, we specified a file - library_id.js, and we use it to have something happen on our page, we will deduce simply alert ().

File library_id.js

        (function ($) {
            Drupal.behaviors.libraryIdBehavior = {
                attach: function (context, settings) {
                    alert ('Hi');
                }
             };};
            ) (jQuery);
        

Next, activate our module, if you have not already done so, or clean the site cache if your module has already been activated. We go to any page of the site and see that the warning window appeared:

Drupal8
Main

Welcome to Drupal8 site

The contents of the main page have not been created yet.

Add material


Excellent library is connected to all pages of the site. Now let's connect it to a certain page, for this, change a little code in the file libraries_id.module:

 
        <? php

        / **
         * @param $ variables
         * Implements hook_preprocess_page ()
         * /
        function library_id_preprocess_page (& $ variables) {

          # Connect the library to the page with NID = 1
          $ current_path = \Drupal :: service ('path.current') -> getPath ();
          if ($ current_path == '/ node / 1') {
            $ variables ['# attached'] ['library'] [] = 'library_id/ library_id';
          }
        }
        

We connect the library for the element type of the form

Also you can connect the library to any type of form element, for example for textarea type, for this we use hook_element_info_alter ():

 
        <? php
        / **
         * @param array $ types
         * Implements hook_element_info_alter ()
         * /
        function library_id_element_info_alter (array & $ types) {
          if (isset ($ types ['textarea']))) {
            $ types ['table'] ['# attached'] ['library'] [] = 'library_id/library_id';
          }
        }
        

Connecting a library in the TWIG template

We can also connect the library in the Twig template:

{{attach_library ('library_id /library_id')}}

We pass the parameters from PHP to the JS file of our library

As in Drupal 7, we can pass a parameter from PHP to the JS file of our library via drupalSettings. For this purpose, in the description of our library (library_id.libraries.yml), as dependencies, specify drupalSettings.

File library_id.libraries.yml
 
        # Testin library
        library_id:
          version: 1.x
          css:
            base:
              css / library_id.css: {}
          js:
            js/library_id.js: {}
          dependencies:
            - core/jquery
            - core/jquery.once
            - core/drupalSettings
        

Accordingly, when connecting a library, we must specify the name of the parameter and its value, which will be available in the JS file of our library.

File library_id.module

 
        <? php

            / **
             * @param $ variables
             * Implements hook_preprocess_page ()
             * /
            function library_id_preprocess_page (& $ variables) {

              # Connect the library to all pages of the site
              $ variables ['# attached'] = array (
                'library' => array ('library_id / library_id'),
                'drupalSettings' => array (
                  'library_id' => array (// Module name
                    'library_id' => array (// Library name
                      'foo' => 'bar',
                    )
                  )
                ),
              );

            }

Accordingly, the transferred values will be available in the drupalSettings of our JS file.

File library_id.js

 
        (function ($) {
            Drupal.behaviors.libraryIdBehavior = {
                attach: function (context, settings) {

                var libValue = drupalSettings.library_id.library_id.foo;
                alert (libValue);
                
                }
              };};
            }) (jQuery);

Connect a remote CSS/JS file

To connect files to the library that are on a remote server, for example, it can be the Yandex.Maps library, you need to specify the full path to the given file and add an additional attribute type: external, so the Yandex.Maps connection will look like this:

File library_id.libraries.yml

 
         # Testin library
         library_id:
          version: 1.x
          css:
            base:
              css/library_id.css: {}
          js:
            https://api-maps.yandex.ru/2.1/?lang=en_US: {type: external}
            js/library_id.js: {}
          dependencies:
            - core/jquery
            - core/jquery.once
            - core/drupalSettings
         
Plus you can pass additional attributes:

File library_id.libraries.yml

 
         # Testin library
         library_id:
          version: 1.x
          css:
            base:
              css/library_id.css: {}
          js:
            https://api-maps.yandex.ru/2.1/?lang=en_US: {type: external, attributes: {async: true}}
            js/library_id.js: {}
          dependencies:
            - core/jquery
            - core/jquery.once
            - core/drupalSettings

Connecting external libraries from CDN

Also we can use external libraries that are in the CDN, for example, the connection of the Colorbox library will look like this:

File library_id.libraries.yml

 
          colorbox:
          remote: http://www.jacklmoore.com/colorbox/
          version: 1.6.4
          license:
            name: MIT
            url: http://www.jacklmoore.com/colorbox/
            gpl-compatible: true
          js:
            https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.6.4/i18n/jquery.colorbox-ar.js: {type: external, minified: true}
            

Embed JS script on the page

You can also embed an inline JS, through the hook_page_attachments() hook, for example, output a normal alert:

File library_id.module

 
           <? php

            / **
             * @param array $ attachments
             * Implements hook_page_attachments ()
             * /
            function library_id_page_attachments (array & $ attachments) {

              # Inline JS
              $ attachments ['# attached'] ['html_head'] [] = array (
                array (
                  '#type' => 'html_tag',
                  '#tag' => 'script',
                  '#value' => 'alert ("Hello world!");',
                  '#attributes' => array (),
                ),
                'Hi',
              );

            }

So, we've dealt with the main aspects of connecting the CSS and the JS. On this I think we can end. Good luck in Drupal 8 study.

Quick Free Quote
We respect your privacy. NO SPAM No selling your personal data.
We will respond to your query & collect further details within 24 hours. Guaranteed!

Support

We are friendly people who love to talk. So go ahead and contact us.

Technologies

Awards & Certification