Building components

6. Drupal Libraries

In Drupal 8, stylesheets (CSS) and JavaScript (JS) are loaded through the same system for modules (code) and themes, for everything: asset libraries.

Drupal uses a high-level principle: assets (CSS or JS) are still only loaded if you tell Drupal it should load them. Drupal does not load all assets on every page because it slows down front-end performance.

Learn more about Drupal libraries.

In the context of the project we are building, we are going to create a library for each individual component we build. Each library will have all the CSS and Javascript (if any), the component needs to render as expected.

IMPORTANT: Drupal libraries are only intended to work in Drupal. They have no effect in KSS Node/Styleguide. So how are we passing styles and javascript to the components in the styleguide? Good question; we have a gulp task in place which compiles all CSS into a single stylesheet (/dist/all/all.css). This stylesheet is automatically appended to the styleguide so all styles are available when a component is rendered in the styleguide.

As for Javascript, how are we appliying it to the styleguide? Even a better question. You are good! 😄 This unfortunately is a manual step, but not a difficult one. We'll do this shortly.

Structure of a library

  • In your editor, open nitflex_dev_theme.libraries.yml (located in your theme's root). You will notice the global library already declared which includes all of the global theme styles that apply to all pages on the site (i.e. font color, font-size, font-family, line-height, etc.). The global library looks something like this (line numbers are for reference purposes only):

    # 1. global:
    # 2.   css:
    # 3.     base:
    # 4.       dist/css/global.css: {}
    
  • Library name. In our case this name will always be the name of our coponent to easily identify what a library is for.

  • The asset we want to include in the library. Usually css and/or js.

  • SMACSS category, in this case base, is loaded before other categories. Drupal 8 loads stylesheets based on the SMACSS ordering of: base, layout, component, state, theme. All of the components we create will usually use the component ordering.

  • The path to your asset in relation to the root of your theme. All assets in the nitflex_dev_theme theme are compiled into dist/css or dist/js. This means for each component we will have an asset stylesheet (i.e. dist/css/heading.css), and if we have a Javascript behavior for the heading component we will also have a JS assets in dist/js/heading.js.

IMPORTANT: The structure of the nitflex_dev_theme.libraries.yml file is very specific and indentation needs to be correct for Drupal to properly read its content. Usually there is a 2 space indentation for each line in a library and if this is not consistent you may run into issues when rendering your components.

There is a lot more to Drupal libraries and we encouorage you to learn more about them in the URL above.

Creating the Movie Card component's library

  1. In your editor open nitflex_dev_theme.libraries.yml

  2. Add the following code:

    movie-card:
     css:
       component:
         dist/css/movie-card.css: {}
    

    Libraries are great for Drupal only loading what you need when you needed to avoid having to load assets that our page or component may never use. This helps with site's performance.

    Note: Don't forget to clear your caches when adding new libraries to your theme.

Attaching a library

Now that the Movie Card component's library is ready, we need to tell Drupal where to use it.

  1. In your editor, open src/components/movie-card/movie-card.twig

  2. Add the following code to the first line in the file:

{{ attach_library('nitflex_dev_theme/movie-card') }}

The attach_library function takes a path parameter which we are declaring by using the theme's namespace (the namespace is created by the Components Libraries module), then the name of the library we want to attach (i.e. nitflex_dev_theme/movie-card).

The Movie Card twig template should now look something like this:

{{ attach_library('nitflex_dev_theme/movie-card') }}

<article class="movie-card {{ attributes ? attributes.class }}"{{ attributes ? attributes|without(class) }}>
  {{ title_prefix }}
  {{ title_suffix }}
  {% if cover_image %}
    <div class="movie-card__cover-image">
      {{ cover_image }}
    </div>
  {% endif %}
  <div class="movie-card__content">
    {%
      include '@nitflex_dev_theme/heading/heading.twig' with {
        "heading": {
          "title": heading.title,
          "url": heading.url,
          "heading_level": heading.heading_level,
          "classes": 'movie-card__heading'
        }
      } only
    %}
    <div class="movie-card__favorites-toggle">
      {% block favorites_toggle %}
        {%
          include '@nitflex_dev_theme/add-to-favorites/add-to-favorites.twig' with {
            url: '#',
          } only
        %}
      {% endblock %}
    </div>
    {% if mpaa_rating %}
      <div class="movie-card__mpaa-rating">
        {% include '@nitflex_dev_theme/mpaa-rating/mpaa-rating.twig' with {
            rating: mpaa_rating
          } only
        %}
      </div>
    {% endif %}
    {% if average_rating %}
      <div class="movie-card__average-rating">
        {% include '@nitflex_dev_theme/average-rating/average-rating.twig' with {
            count: average_rating
          } only
        %}
      </div>
    {% endif %}
    {% if synopsis %}
      <div class="movie-card__synopsis">
        {{ synopsis }}
      </div>
    {% endif %}
  </div>
</article>

With the code above, we are telling Drupal that whenever we render the moivie card component, its library should be attached so the styles for the component can be applied to it.

Adding Javascript to KSS Node

As explained before, Drupal libraries have no effect on KSS Node or the styleguide. In order for the components to make use of the javascript we've written we need to manually add the script to the styleguide.

  1. In your text editor, open nitflex_dev_theme/src/style-guide/builder/index.twig (This is the builder template responsible for building the styleguide). There are several types of builders (HTML, Handlebars, etc.), but for Drupal we use the Twig builder, which uses twig.js.

  2. Scroll to the very bottom of the file where you will see other Javascripts references.

  3. A good place to add your newly created script is just above the {{ scripts|raw }} tag.

Example of a custom script to add to the styleguide:

<script src="../js/movie-card.js"></script>

As you can see we added the movie-card.js script with a relative path to the styleguide. The Compile Gulp tasks automatically compiles all javascript code found in the components into individual files inside dist/js.

Note: Confirm the right path for your scripts.

Next steps

Create and attach libraries for` all components

Now that we know how Drupal Libraries work and how to create them, go ahead and create a new library for each component you have built thus far, then attach each library to the correspsonding component.

🔥 TIP

Ordering libraries alphabetically is a great way to quickly find the right library as your components catalog grows.

Resources

Video presentation on Libraries

Mediacurrent's Director of Front-End Development, Zack Hawkins, explains libraries in detail: https://www.youtube.com/watch?v=V8hnfxSx4Ck


Previous exercise: Build the Movie Card component

Next exercise: Build the Featured Movie component

results matching ""

    No results matching ""