Theming Drupal Sites

Themes in Drupal are responsible for the look and feel of your site. They provide the HTML markup, CSS, typography, images, and interactive experience that people encounter when they view your site. Your site's theme is responsible for that oh-so-important first impression of your organization when they visit your Drupal site. This series is a collection of all of our Drupal Theming tutorials -- everything you need to know to create amazing Drupal themes.

As you might imagine, there’s a lot to learn about developing themes for Drupal, we’ve tried to break things up into manageable units but the truth is, much of it’s intertwined. Our goal is to make it easy to skip over the stuff you already know, and just as easy to get more information about any related topic you might not be familiar with. Feel free to go through all the tutorials in order, or jump around to those that answer your immediate questions.

Get started now!

Tutorials in this course
Categories
Drupal 8, 9, and 10
More information

Themes are the part of Drupal that you, and anyone else visiting your Drupal powered application, see when they view any page in their browser. You can think of a theme as a layer, kind of like a screen, that exists between your Drupal content and the users of your site. Whenever a page is requested Drupal does the work of assembling the content to display into structured data which is then handed off to the presentation layer to determine how to visually represent the data provided.

Drupal themes are created by front-end developer. Frequently referred to as themers, or theme developers. Themes consist of standard web assets like CSS, JavaScript, and images, combined with Drupal-specific templates for generating HTML markup, and YAML files for telling Drupal about the file and features that make up each individual theme.

In this tutorial we'll:

  • Explain what a Drupal theme is.
  • Explain the role of a Drupal themer in the process of building a Drupal site.
  • Get a high level overview of the types of files/code that themes are made of.

By the end of this tutorial you should be able to explain what a Drupal theme is, and the kind of work a Drupal theme developer will be expected to do.

Categories
Drupal 8, 9, and 10
More information

Before visitors to your site will see the pages displayed using a theme the theme needs to be installed and set as the default. This is true whether it's a custom theme you wrote yourself, or a contributed theme you downloaded from Drupal.org. Installing themes can be done either via the user interface, or using Drush. Once a theme is installed, users of your site will see all public facing page rendered using that theme. Themes that are no longer being used can safely be uninstalled.

In this tutorial we'll:

  • Demonstrate how to install a theme and make it the default using both the UI and Drush.
  • Learn to differentiate between installed themes, default themes, and uninstalled themes.
  • Configure our site to use an administration theme for the administrative pages.

By the end of this tutorial you should be able to install a theme and make it the one visitors to your site see by default.

Categories
Drupal 8, 9, and 10
More information

Each theme is a collection of files that define a presentation layer for Drupal. While only a THEMENAME.info.yml file is required, most themes will contain other files as well. Some are Drupal-specific, and need to follow a strict naming convention and be placed in the appropriate place for Drupal to find them. Others are standard front-end web assets like CSS, JavaScript, and image files that can be placed anywhere within the theme's code.

In this tutorial we'll learn about:

  • The various types of files you can expect to find in a theme directory
  • Where in the Drupal code base your theme directory should live
  • Keeping the directory and all the files within organized

By the end of this tutorial you should be able to explain where a Drupal theme should be placed in a project's code base, and the types of files one can expect to find in a theme.

Categories
Drupal 8, 9, and 10
More information

When it's time to start a custom Drupal theme from scratch (especially if you're new to Drupal theming), we recommend using Starterkit. Starterkit helps you get a new theme up and running by scaffolding a set of theme files with sensible defaults, saving you from a bunch of repetitive work.

In this tutorial we'll:

  • Learn what Starterkit is
  • Discuss when you should--and should not--use Starterkit
  • Walk through how to use Starterkit to generate a new Drupal theme

By the end of this tutorial you should be able to explain the use case for Starterkit and understand how to use it to start a new custom theme.

Categories
Drupal 8, 9, and 10
More information

Info files, aka THEMENAME.info.yml files, provide Drupal with metadata about your theme, the features it supports, and the regions that it defines. All themes are required to have a THEMENAME.info.yml file, and creating one is generally the first step you'll take when creating a new theme.

In this tutorial we'll:

  • Create a new .info.yml file and define a new theme
  • Review the required key/value pairs of an .info.yml file
  • Enable our new theme in the Drupal UI

By the end of this tutorial you'll be able start a new theme by creating the required *.info.yml file and better understand its contents.

Categories
Drupal 8, 9, and 10
More information

One important aspect of theme administration is the configuration of global and theme-specific settings. In this tutorial, you will learn where theme settings are configured in Drupal's administrative interface, the difference between global and theme-specific settings, and what each global setting refers to on a base installation of Drupal with a custom theme installed.

Categories
Drupal 8, 9, and 10
More information

Some, but not all, themes come with administrator-configurable settings that you can change through the UI. These might allow you to upload your own logo, choose between a couple of different pre-defined layouts, or turn features of a theme on or off. In this tutorial we’ll look at where you can find these theme settings if they exist, and how to go about changing them.

Drupal 8, 9, and 10
More information

In Drupal's Appearance UI, all themes get a theme settings form. As a theme developer, you can customize the theme settings form, enabling site administrators to have more control over the appearance of the theme.

In this tutorial, we'll show you how to add admin-configurable settings to your theme. In the process of doing this, we'll use a variety of theme and module development skills and assume you have some familiarity with using Drupal's Form API, Configuration API, and theme system (see Prerequisites).

By the end of this tutorial, you will be able to provide custom theme settings that an administrator can use to modify the appearance of the theme.

Categories
Drupal 8, 9
More information

Bartik is a core theme in Drupal. As a default theme for Drupal, it serves as an instructive example of a well-developed responsive theme. In this tutorial, we'll tour and explore Bartik, identify its primary features, and explain the use case for the Bartik theme and what you can learn from it.

Categories
Drupal 8, 9, and 10
More information

Contributed and custom themes can ship with a thumbnail screenshot that will be used to represent the theme when listing themes in the administration UI.

In this tutorial you'll learn how to:

  • Prepare your site for the screenshot
  • Create a screenshot of your theme
  • Define a screenshot file for your theme in the THEMENAME.info.yml file
Categories
Drupal 8, 9, and 10
More information

Drupal comes with all of its caching features enabled by default. This improves response time, but can be frustrating for themers as it makes it harder to preview the changes you make to template files.

In this tutorial we'll look at:

  • Why these features are enabled by default
  • How the theme layer leverages Drupal's caches
  • Why you should learn to disable them when doing development
Categories
Drupal 8, 9, and 10
More information

Themes define the regions that are available for site administrators to place blocks in, creating a layout framework within which the components that compose a page can be placed. As a theme developer you'll need to determine what regions are necessary to accommodate your design's layout, while also ensuring it'll work with the way Drupal uses blocks to place content onto the page. Deciding what regions to create requires knowledge of how Drupal works and a clear vision of the design you're trying to achieve.

In this tutorial we'll:

  • Explain what regions are and how they relate to themes
  • Describe how regions are handled internally within Drupal
  • Demonstrate things to keep in mind when planning the regions for your custom theme

By the end of this tutorial you should be able to describe what a region is, explain how Drupal themes use regions to place content, and get started dissecting your own designs into regions.

Categories
Drupal 8, 9, and 10
More information

Customizing the available regions in your theme is one of the first things you'll do when creating your own themes. Doing so gives you complete control over where content is displayed on the page, and the markup involved. Adding regions to a theme is a two-step process that involves editing your theme's THEMENAME.info.yml file and updating your page.html.twig file.

In this tutorial we'll:

  • Declare one or more new regions in our themes THEMENAME.info.yml file.
  • Output the content of those regions in our theme via the page.html.twig file.

By the end of this tutorial you should be able to add or edit the regions a theme provides. Also, you'll ensure that blocks placed into regions are displayed by outputting the regions in the page template.

Categories
Drupal 8, 9, and 10
More information

Custom themes in Drupal must be configured to inherit settings, templates, and other assets from a parent theme. Which base theme you use is configurable. This allows theme developers to use a different set of markup as the starting point for their theme, organize various theme assets into a more maintainable structure, and more. All of this is made possible because of how Drupal's theme layer uses a chain of inheritance when assembling all the parts of a theme.

Base themes are also a powerful way to encapsulate standards and best practices into a reusable code base. You'll find dozens of contributed base themes on Drupal.org that can serve as a great starting point, especially if you're planning to work with an existing design framework like Bootstrap or Susy Grids. Or if you want to leverage modern JavaScript bundling without setting up Webpack on your own.

In this tutorial we'll:

  • Learn what base themes and subthemes are
  • Look at a few examples of template inheritance and how that works
  • Discuss some use cases for theme inheritance

By the end of this tutorial you'll know how to declare the base theme that your theme builds upon.

More information

Drupal core comes with a few base themes: Stable, Stable 9, Classy, and Stark. Each one has a different intended use case. And all of them are useful as a reference for building your own themes.

In this tutorial we'll:

  • Learn what each of the base themes included in Drupal core is intended to be used for
  • Compare the output from the base themes with a focus on Stable and Classy

By the end of this tutorial you'll be able to explain the use case for each of the base themes included with Drupal core and make an informed decision about which, if any, to use when creating your own custom themes.

Categories
Drupal 8, 9
More information

Make your theme a subtheme of a base theme, allowing it to inherit all the base theme's templates and other properties. When creating Drupal themes it is common to use the Classy theme provided with Drupal core as a base theme to jumpstart your development.

In this tutorial we'll learn how to:

  • Use the base theme key in our theme's THEMENAME.info.yml file
  • Make our Ice Cream theme inherit from the Classy theme, or any other theme

By the end of this tutorial you should be able to tell Drupal that your theme is a child of another theme and should inherit all of the parent theme's features.

More information

Making Drupal fast by default implies having caching layers and CSS and JavaScript aggregation utilities enabled out-of-the-box. As a theme developer this can be annoying, because you must clear these various caches in order to preview any changes. In addition, inspecting variables with debugging tools often produces PHP errors. We'll make some recommendations for PHP settings on your local environment that can prevent these errors from happening so often.

By the end of this tutorial, you should be able to:

  • Set up your local Drupal site for theme development
  • Prepare your local development environment for working on and debugging themes
Categories
Drupal 8, 9
More information

Stark is one of the themes bundled with Drupal. It is intentionally bare bones and its purpose is to help Drupal theme and module developers get to the heart of Drupal's system templates. In this tutorial, we'll explore Stark and its primary features and discuss the various reasons for utilizing the Stark theme.

Categories
Drupal 8, 9, and 10
More information

Knowing how to clear Drupal's cache is an important skill for any developer. You'll likely find yourself doing it frequently in order to get Drupal to register the changes you make to your code, or other updates you make via the UI. It is also a good first step to trouble shooting problems with your Drupal site: Clear the cache before you do any other debugging to ensure it's not just a bad cache entry.

Categories
Drupal 8, 9, and 10
More information

Template files are responsible for the HTML markup of every page generated by Drupal. Any file ending with the .html.twig extension is a template file. These files are composed of standard HTML markup as well as tokens used by the Twig template engine to represent dynamic content that will be substituted into the HTML markup when the template is used. As a theme developer, you'll work with this a lot.

In this tutorial we’re going to learn about:

  • What template files are, and how they fit into the big picture of creating a theme
  • How template files are used in order to allow theme developers to modify the HTML markup output by Drupal
  • Naming conventions for, and specificity of, template files
Categories
Drupal 8, 9, and 10
More information

This tutorial demonstrates how to locate the template file that is currently being used to render an element and override it in your own theme. This is an important skill for anyone who wants to make changes to Drupal's default HTML markup.

In this tutorial we'll:

  • Override the node.html.twig template in our theme
  • Make changes to the markup
  • Create a content-type-specific template override like node--CONTENT_TYPE.html.twig

By the end of this tutorial you should be able to modify the HTML markup used to display a node, or any other element of the page generated using a template file.

Categories
Drupal 8, 9, and 10
More information

If you want to make changes to the HTML markup of any element on the page you need to first figure out the theme hook or base name of the template file used to generate it. This information is required to override the template in your custom theme.

There are other situations in which knowing the theme hook name of a template file is useful. Including determining which preprocess function affects a template, and which template theme hook suggestions can be used.

In this tutorial we'll learn:

  • How to figure out the theme hook name for any template

By the end of this tutorial you should be able to use the output from Twig's debugging mode to determine the theme hook name of any template file.

Categories
Drupal 8, 9, and 10
More information

Knowing how to inspect the variables available within a template file enables you to discover all of the dynamic content in a Twig file, not just that which is already being used.

In this tutorial, we'll learn how to use {{ dump() }}, kint(), vardumper(), and XDebug to inspect variables in a template file.

Drupal 8, 9, and 10
More information

The Render API consists of two parts: structured arrays that provide data and hints about how that data should be rendered, and a rendering pipeline that can be used to render these arrays into various output formats. Understanding at least the basics of how the Render API works, the difference between elements and properties, and the concept of callback functions is an integral part of learning Drupal.

In this tutorial we'll:

  • Look at the fundamentals of the Drupal Render API
  • Point to additional material to provide more detail about the inner workings of the Render API and how content is output in Drupal
Categories
Drupal 8, 9, and 10
More information

Every theme can contain an optional THEMENAME.theme file. This file contains additional business logic written in PHP and is primarily used for manipulation of the variables available for a template file, and suggesting alternative candidate template file names. Themes can also use this file to implement some, but not all, of the hooks invoked by Drupal modules.

In this tutorial we'll learn:

  • The use case for THEMENAME.theme files, and where to find them
  • The different types of functions and hooks you can implement in a THEMENAME.theme file

By the end of this tutorial you should be able to know how to start adding PHP logic to your custom theme.

Categories
Drupal 8, 9, and 10
More information

Preprocess functions allow Drupal themes to manipulate the variables that are used in Twig template files by using PHP functions to preprocess data before it is exposed to each template. All of the dynamic content available to theme developers within a Twig template file is exposed through a preprocess function. Understanding how preprocess functions work, and the role they play, is important for both module developers and theme developers.

In this tutorial we'll learn:

  • What preprocess functions are and how they work
  • The use case for preprocess functions
  • The order of execution for preprocess functions

By the end of this tutorial you should be able to explain what preprocess functions are and the role they play in a Drupal theme.

More information

Preprocess functions are specially-named PHP functions that allow themes and modules to modify the variables passed to a Twig template file. They are commonly used by themes to alter existing variables before they are passed to the relevant template files. For example; Changing the makeup of render array so that it renders an <ol> list instead of a <ul> list. Or appending data to the label of a node depending on custom logic.

In this tutorial we'll:

  • Define a new preprocess function in our theme's .theme file
  • Use the preprocess functions to modify the content of an existing variable before it's used in Twig

By the end of this tutorial you should be able to define new preprocess functions in a theme (or module) that manipulate the variables for a specific Twig template file.

Categories
Drupal 8, 9, and 10
More information

Preprocess functions are specially-named functions that can be used to add new variables to a Twig template file. They are commonly used by themes to add new variables based on custom PHP logic and simplify accessing the data contained in complex entity structures. For example: adding a variable to all node.html.twig template files that contains the combined content a couple of specific fields under a meaningful name like {{ call_to_action }}. Modules use preprocess functions to expose the dynamic data they manage to Twig template files, or to alter data provided by another module based on custom logic.

In this tutorial we'll learn how to:

  • Use PHP to perform some complex logic in our theme.
  • Store the resulting calculation in a variable.
  • Make that variable available to a Twig template file.

Example use cases for adding variables with preprocess functions include:

  • Anytime calculating the value to output in a template requires logic more complex than an if/else statement.
  • Anytime the desired value requires additional string manipulation beyond what can be easily accomplished using an existing Twig filter or function.

By the end of this tutorial you should be able to expose new variables to a Twig template file by defining a preprocess function in either a module or a theme.

Categories
Drupal 8, 9, and 10
More information

When determining which template file to use to theme an element, Drupal uses the list of theme hook suggestions to look for the best match. This allows for fine-grained control over how things appear based on dynamic state and contextual information in your application. The list of theme hook suggestions varies for each base template, so we need a way to figure out our options.

In this tutorial we'll look at:

  • How to determine the list of valid theme hook suggestions for any template file
  • How theme hook suggestions are added by modules and themes

By the end of this tutorial you should be able to explain how theme hook suggestions are added, and determine the valid suggestions for any template file.

More information

Themes and modules can alter the list of theme hook suggestions in order to add new ones, remove existing ones, or reorder the list. This powerful feature allows for the definition of custom logic in your application that can tell Drupal to use different templates based on your own unique needs. You might for example; use a different page template for authenticated users, or a custom block template for someone's birthday.

In this tutorial we'll cover:

  • Adding new theme hook suggestions from a theme using hook_theme_suggestions_HOOK_alter()
  • Altering the list of theme hook suggestions
  • Removing theme hook suggestions
  • Reordering the list of theme hook suggestions
Categories
Drupal 8, 9, and 10
More information

Twig is the default template engine for Drupal. If you want to make changes to the markup that Drupal outputs you're going to need to know at least some Twig. In this tutorial, we will outline the role that Twig now plays in Drupal, how Twig impacts the theming experience, and where to find additional resources for learning Twig.

At the end of this lesson, you'll be able to:

  • Describe the role that Twig plays in creating Drupal themes
  • Explain how Twig impacts the theming experience in Drupal
  • Locate additional resources for learning Twig
Categories
Drupal 8, 9, and 10
More information

To read a Twig template file, you'll need to recognize Twig's syntax delimiters. Twig has three syntax delimiters: one for printing out variables, another for performing actions or logic, and lastly, one for comments, also used for docblocks.

In this tutorial we'll:

  • Explore each of Twig's 3 syntax delimiters.
  • Show examples of each from Drupal's core template files.

By the end of this tutorial you should be able to recognize each of Twig's syntax delimiters and understand what the engine will do when it encounters them.

Categories
Drupal 8, 9, and 10
More information

Twig has a special syntax for accessing array keys and objects, also known in Twig as variable attributes. In this tutorial, we'll cover the period or dot (.) operator to access a variable attribute, as well as subscript or square-bracket syntax, useful for when the key of the array contains special characters, like a dash (-) or pound sign (#). We'll also look at the logic Twig uses to find the matching attribute in an array or object.

Categories
Drupal 8, 9, and 10
More information

Many of the variables that you have access to inside of a Twig template file are arrays. For example a list of values for a multi-value field, or a set of error messages generated when validating a form submission. In order to work with arrays in Twig you'll need to understand how for loops work. This is essential information for anyone creating Drupal themes.

In this tutorial we'll cover:

  • Using the for tag to iterate over an array
  • Using the loop variable inside of a for loop for additional context
Categories
Drupal 8, 9, and 10
More information

The ability to loop over an array of values in a Twig template and print out each value individually is an important skill for anyone developing themes for Drupal. Common scenarios include: loop over the values of a multiple value field; iterate through a list of links; and display error messages at the top of forms. This tutorial will provide an example of using the Twig for function to iterate over a list, or a subset of a list.

In this tutorial we'll cover how to:

  • Output values from a multi-value field in an unordered list.
  • Add first and last classes to the first and last items in a list by using the Twig loop variable.

By the end of this tutorial you should be able to print out the values of an array as individual list items using a loop in Twig.

Categories
Drupal 8, 9, and 10
More information

In Twig, you can modify variables using functions or filters. Twig has a bunch of built-in functions and filters. Drupal extends Twig to provide a few handy Drupal-specific functions and filters as well.

In this tutorial, we'll look at:

  • What are functions and filters?
  • How to use functions and filters in Twig
  • Detailed information about the Drupal-specific functions and filters and their use case
Categories
Drupal 8, 9, and 10
More information

Do you cringe at the sight of untidy whitespace or (gasp) no whitespace at all when you View Source? Learn how to tame whitespace in Twig template files in this tutorial. By the end of this lesson, you will be able to recognize how Twig controls whitespace and how you can do the same in your Drupal template files.

Categories
Drupal 8, 9, and 10
More information

In order to ensure that all user interface strings in your application can be translated using Drupal's localization system, any text you add to templates needs to use either the t filter or the {% trans %} tag. Anyone creating themes or editing template files associated with a theme or a module should know how to use these two utilities.

In this tutorial we'll look at:

  • How to use the t filter and {% trans %} tag in a Twig template
  • The differences between the two, and how to determine which one to use
  • How to translate strings assigned to variables in preprocess functions using the PHP t() function
Categories
Drupal 8, 9, and 10
More information

Theme developers often need to add or remove classes and other attributes from an HTML tag. Template files handle this with a special attributes object that contains the attributes and their values, as well as a handful of powerful methods to help manage these attributes.

In this tutorial we’ll cover:

  • Adding/removing classes from elements in a Twig template
  • The attributes object
  • Examples of common tasks using various helper methods on the attributes object
Drupal 8, 9, and 10
More information

Before you can create a path or link to another page on your site, you'll need to know the route (unless there is already a variable available for the URL you need). Finding a route can be a tricky task unless you have the right tools. In this tutorial, we'll show how tools like Webprofiler, Drush, and Grep can be used to get route information for a page, so that you can use functions that need a route as a function parameter.

In this tutorial we'll:

  • Learn how to determine the route or path of an internal page.
Categories
Drupal 8, 9, and 10
More information

If you want to create a link to a internal page in a Twig template--and there's not already a variable in the template that contains the URL you want to link to--you'll need to determine the route of the thing you want to link to and then use the Twig url() or path() functions to generate appropriate URLs. In most cases when you want to create a link to an entity that is being output by the current template there's an existing helper variable to use. For example, in a node.html.twig template file there's a {{ url }} variable that points to the current node. For other scenarios, like hard-coding a link to the /about page, you'll need to do a little more work.

In this tutorial we'll:

  • Use the Twig url() and path() functions to create full URLs for navigation

By the end of this tutorial you should be able to create links to any internal page via Twig.

Categories
Drupal 8, 9, and 10
More information

More often than not, templates in a theme share common elements: the header, footer, sidebar, or more. In Drupal, themes created with a Twig template can be decorated by another one. This template inheritance allows you to build a base "layout" template that contains all the common elements of your layout defined as blocks. A child template can extend the base layout and override any of its defined blocks. This helps prevent code duplication, and keeps your theme more organized.

This tutorial is for theme developers who want to reduce code duplication in their themes, or anyone seeking to better understand how Twig template inheritance works. We'll cover:

  • What the Twig block and extends tags do
  • An example use-case for template inheritance
  • How to extend a Twig template from another theme or module
  • How to include other Twig templates
Drupal 8, 9, and 10
More information

Any text that will be displayed to user as part of your application's user interface should be passed through the t() function, or an equivalent, so that it can be translated into other languages as needed. This tutorial will look at how to use the t() function.

This tutorial contains information that applies to anyone writing modules or themes. And many of the tutorials you read on this site and on the web in general will expect that you understand how basic string translation works.

In this tutorial we'll look at:

  • Passing strings through the t() function or equivalent so they are available for translation
  • Using placeholders for dynamic content in translatable strings
  • Tips for making your code's interface strings easier to translate
Categories
Drupal 8, 9, and 10
More information

An asset library is a bundle of CSS and/or JavaScript files that work together to provide a style and functionality for a specific component. They are frequently used to isolate the functionality and styling of a specific component, like the tabs displayed at the top of each node, into a reusable library. If you want to include CSS and/or JavaScript in your Drupal theme or module you'll need to declare an asset library that tells Drupal about the existence, and location, of those files. And then attach that library to a page, or specific element, so that it gets loaded when needed.

In this tutorial we’ll:

  • Define what an asset library is.
  • Explain why asset libraries are used to include JavaScript and CSS files.
  • Look at some example asset library definitions.

By the end of this tutorial you should be able to define what asset libraries are, and when you'll need to create one.

Categories
Drupal 8, 9, and 10
More information

New asset libraries can be defined by either modules or themes. In order to define a new asset library you need to create the requisite CSS and JavaScript files, and a new THEMENAME.libraries.yml, or MODULENAME.libraries.yml file that aggregates them together and provides metadata about the library itself and any dependencies.

In this tutorial we’ll:

  • Look at the structure of a *.libraries.yml file and demonstrate how to combine a couple of CSS and JS files together into an asset library that can be used in a theme or a module
  • Look at how one asset library can declare that it is dependent on another in order to ensure the assets from the dependency are loaded as well

By the end of this tutorial you should know how to define a new asset library in either a module or a theme.

Categories
Drupal 8, 9, and 10
More information

Once you've defined an asset library you'll need to tell Drupal when you want to add the CSS and JavaScript that it includes to the page. Ideally you'll do so in a way that allows Drupal to only add the corresponding assets on pages where they are needed.

You can attach a library to all pages, a subset of pages, or to elements in a render array. This allows you to have some assets that are global, and others that get loaded on an as-needed basis. To attach a library you'll need to know both its name and prefix, and then use one of the techniques outlined below to let Drupal know when to include it.

In this tutorial, we'll look at attaching asset libraries:

  • Globally, via your THEMENAME.info.yml file
  • Conditionally, via a preprocess function using the #attached render array property
  • Inside of a Twig template file

By the end of this tutorial you should be able to attach asset libraries in various different ways depending on your use case.

More information

As a theme developer you can extend an existing asset library to include custom CSS and/or JavaScript from your theme. This is useful when you want to add styles or behaviors to components provided by Drupal core or another module.

Sometimes there are CSS or JavaScript asset libraries attached to the page by Drupal core, a contributed module, or another theme, that do something you don't like, and you want to change it or even exclude it all together. There are a couple of different ways that themes can override, alter, or extend, an existing asset library in order to modify the CSS and JavaScript that get attached the page by other code belonging to another theme or module.

In this tutorial we'll learn how to:

  • Extend an existing asset library using libraries-extend, so that our custom CSS and JavaScript is included whenever that library is used.
  • Override an existing asset library using libraries-override, to alter the definition of the library, and replace or exclude individual assets (or the entire library).

By the end of this tutorial you should be able to use your custom theme to override, extend, or alter any of the asset libraries added to the page by another theme or module.

Categories
Drupal 8, 9, and 10
More information

JavaScript is used and loaded in special ways within a Drupal site. JavaScript is loaded via asset libraries and Drupal core provides a bunch of different JavaScript libraries that you can load and use in your module or theme. This tutorial provides a brief orientation to some of the JavaScript included in core.

In this tutorial we'll:

  • Preview the JavaScript ecosystem in Drupal
  • Find pointers to tutorials where you can learn more about adding JavaScript to a theme or module
  • Learn about examples of JavaScript in Drupal core that are useful to review for learning purposes

By the end of this tutorial you should have a good overview of how JavaScript is used throughout Drupal core.

Categories
Drupal 8, 9, and 10
More information

In developing the theme for your website it's important to take accessibility into account. Making your site available and functional for as many users as possible is always a good idea. Progressive enhancement and graceful degradation are key, but how do you go about accounting for the minute differences between browser capabilities? This is where the Modernizr.js library can help you out.

Modernizr is a collection of browser detection tests which allow you, in either CSS or JavaScript, to determine if a particular browser supports a large list of features. From there it can automatically add classes to your page depending on the results of a particular feature test. It can also be used to create additional custom tests. In this tutorial we'll take a look at a few of the feature detection tests that Modernizr natively supports as well as how a custom test can be added to a Drupal theme.

More information

Underscore.js is a very small library which provides several utility functions and helpers to make working with JavaScript a little bit easier. In this tutorial we'll take a look at a part of the library, learn where the full library is documented, and see how we can make use of Underscore.js in a custom block on our Drupal site.

Categories
Drupal 8, 9, and 10
More information

It's probably not too surprising that a library called Backbone aims to provide structure to your front-end JavaScript code and applications. In this tutorial we'll take a look at how Backbone.js goes about achieving that goal, and how you can make use of it on your Drupal site. We'll first take a high-level look at the main components that make up the Backbone.js library. With that basic understanding in place we'll look at an example of how you might integrate Backbone.js into a Drupal site.

More information

Anyone writing JavaScript for Drupal should use the Drupal.behaviors API when writing their custom JavaScript functionality. Doing so ensures that your JavaScript is executed at the appropriate times during the life cycle of a page, such as when the page loads, or after new DOM elements have been added via an AJAX request.

In this tutorial we'll look at:

  • The problem that Drupal.behaviors solves
  • How to use Drupal.behaviors when writing your JavaScript code

By the end of this tutorial you should be able to explain what the Drupal.behaviors API is, and be able to use it in your own JavaScript.

Categories
Drupal 8, 9, and 10
More information

Maybe you've heard of anonymous closures but you're not quite sure how they apply in Drupal, or why using them is considered a best-practice. Anonymous closures allow you to avoid accidentally clashing with anything in the global scope, as well as to alias the jQuery object to the more commonly used $. This is necessary because Drupal runs jQuery in no-conflict mode. This tutorial will look at the syntax used for placing your custom JavaScript code inside an anonymous closure, and why it's a good idea to do so.

In this tutorial we'll:

  • Explain what a closure is (briefly), and what immediately invoked function expressions are
  • Show how typically Drupal JavaScript gets wrapped in a closure
  • Provide a copy/paste example you can use in your own code

By the end of this tutorial you should be able to explain what an anonymous closure is, and how to use one in your custom JavaScript for Drupal.

More information

In Drupal, whenever we output markup it's best practice to use a Twig template or a theme function. But whenever you need to output DOM elements within JavaScript the best practice is to use the Drupal.theme function. This function ensures that the output can be overridden just like the HTML output by Twig. This tutorial covers how to use the Drupal.theme function in your JavaScript when inserting DOM elements, as well as how to replace the markup output by other JavaScript code that is using the Drupal.theme function.

Categories
Drupal 8, 9, and 10
More information

You may know that Drupal provides utility PHP functions for manipulating and sanitizing strings. Drupal also provides JavaScript functions for the same purpose. The two most useful are Drupal.checkPlain and Drupal.formatPlural. Drupal.checkPlain lets you ensure a string is safe for output into the DOM; it is useful when working with user-provided input. Drupal.formatPlural ensures that a string containing a count of items is pluralized correctly. This tutorial will show you where you can find documentation for and example use-cases of both.

More information

Sometimes your JavaScript needs to insert new strings into the user interface. In order to ensure that those user-facing strings can be translated into other languages, just like the rest of Drupal's user interface, you should make sure and use the Drupal.t function anytime you output a string of text.

More information

It's often useful to pass dynamically calculated values from the server to the client in order to make them available to your front-end JavaScript. Your JavaScript might need to know something particular about the user currently visiting the site or the value of a particular configuration variable. In this tutorial, we'll look at how Drupal can pass these values from the PHP code that executes during a page load to the front-end JavaScript in your theme.

In order to do this, we'll need to:

  • Explain how drupalSettings bridges the gap between PHP and JavaScript
  • Generate values for settings in PHP and make them available to JavaScript
  • Make use of PHP generated settings within your JavaScript code
Categories
Drupal 8, 9, and 10
More information

ESLint is the linting tool of choice for JavaScript in Drupal. In this tutorial we’ll show how to install the ESLint application and then use it to verify that your JavaScript files are meeting the Drupal coding standards.

Drupal (as of version 8.4) has adopted the Airbnb JavaScript coding standards. In this tutorial, we'll walk through how to install the necessary package dependencies to run eslint on JavaScript files within your Drupal site.

Categories
Drupal 8, 9, and 10
More information

You've got a slick responsive theme for your Drupal site that's been implemented in CSS using media queries. But the content and images on your site will regularly be updated and you want to use the Responsive Images module to create responsive image style field formatters that you can apply to image field display settings.

In this lesson, we'll review the concepts of breakpoints and media queries so that you can better understand what's going on when you encounter them in non-CSS file contexts like configuration forms for responsive image styles or breakpoint YAML files.

By the end of this tutorial, you should have an understanding of what breakpoints are, how they are expressed in media queries, and how they are relevant in the context of Drupal.

Categories
Drupal 8, 9, and 10
More information

Drupal's Breakpoint module defines a "breakpoint" plugin type that modules or themes can implement via a breakpoints configuration file. So, in order to make their breakpoints discoverable, themes and modules define their breakpoints in a THEME-OR-MODULE.breakpoints.yml file located in the root of their directory.

In this tutorial, you'll learn about the structure of a breakpoints configuration file and why you would want to use one. We’ll cover the kinds of metadata you can include in a breakpoint file, including key, label, mediaQuery, weight, multipliers, and breakpoint group. Throughout, we'll look at some examples of breakpoint configuration files available in Drupal themes and modules.

Categories
Drupal 8, 9, and 10
More information

As we learned in the What Is a Breakpoints YAML file? tutorial, modules and themes can expose their site's CSS breakpoints and media queries to other Drupal modules and themes by implementing a breakpoints YAML file. In that tutorial, you also learned about the structure of a breakpoints configuration file and why you'd want to create one. In this tutorial, we’ll walk through the process of creating an example breakpoints file step-by-step.

By the end of this lesson, you should be able to create a working breakpoints YAML file in a theme or module. We'll test it out by enabling Drupal's Responsive Image module, where we'll be able to see it listed in the configuration form for creating a new responsive image style.

Categories
Drupal 8, 9, and 10
More information

The Responsive Image module provides a process for transforming images uploaded through image fields into responsive images. This is accomplished through the configuration of responsive image styles. The configuration form for adding and editing responsive image styles is quite extensive. In this tutorial, we'll go through this form and learn what each option entails. By the end of this lesson, you should have a good understanding of the various options in the responsive image style configuration form.

Categories
Drupal 8, 9, and 10
More information

You might already be familiar with image styles in Drupal. Image styles are a popular and commonly used feature of Drupal because they enable your site's content creators to upload an image once, but have it displayed at various sizes and resolutions depending on its context. Image styles are configured and then applied to an image field's display settings, whether using view modes, Views field settings, or other contexts. Responsive image style field formatters are applied in the same exact way, but the process of creating responsive image styles is a bit different.

Using responsive image styles as image field formatters enables your Drupal site to produce specific HTML markup for images so that either:

  1. The browser can choose an appropriately sized image source, given the size of the user device's viewport size
  2. You can dictate to the browser which image sources to use at different breakpoints.

In the first case, the resulting markup uses the srcset and sizes attribute in an <img> element. In the second case, <picture> and <source> elements are generated in conjunction with the <img> tag.

It is also possible to create a responsive image style that just provides alternate images depending on the display-density (i.e. 1.5x or 2x) of the user device.

In this tutorial, we'll look at three use cases for responsive images, how those use cases are handled in HTML, and how they can be handled using Drupal's Responsive Image module. By the end of this tutorial, you should be ready to create a responsive image style appropriate for your Drupal site.

More information

In this tutorial, we're going to add a responsive image style to an image field on the Article content type. This will add the srcset and sizes attributes to the output <img> element, providing media conditions, width descriptors, and a set of image sources for the browser to choose from, depending on the user device's viewport size.

This solution, especially when used in conjunction with CSS, will provide flexible, fluid, and faster-loading images for your site, and will work for probably 80% of use cases. It does not provide "art direction", that is, making cropping, aspect ratio, or orientation changes to an image. This solution also provides for different display-densities, like 1.5x and 2x image sources without the need for display-density descriptors.

Another benefit of this solution is that it uses the Responsive Image module's breakpoint configuration file, so there is no need for you to create a breakpoint file in your theme to implement this flavor of responsive image style.

More information

By default, individual forms in Drupal are not output using Twig template files. It's possible to associate a form with a Twig template file by creating a new theme hook, and then referencing that theme hook from the $form array that defines the form. Doing so allows theme developers to customize the layout of the elements in the form using HTML and CSS.

This is useful when you want to change the layout of the entire form. For example, putting the elements into 2 columns. If you want to change individual elements in the form, you can often do so by overriding element specific Twig template files.

In this tutorial, we'll:

  • Learn how to create a new theme hook that can be used to theme an element in a render array.
  • Associate the $form we want to theme with the new theme hook we created.
  • Create a Twig template file for the theme hook that will allow us to lay out the form elements using custom HTML.

By the end of this tutorial, you should be able to associate a Twig template file with any form in Drupal, so that you can customize its layout using HTML and CSS.

This course appears in the following guides:
Categories
Theming
Drupal 7, 8, 9, and 10