Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Modernizing Drupal 10 Theme Development
Modernizing Drupal 10 Theme Development

Modernizing Drupal 10 Theme Development: Build fast, responsive Drupal websites with custom theme design to deliver a rich user experience

eBook
€15.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Modernizing Drupal 10 Theme Development

Setting up a Local Environment

Do you have a Drupal website you need to style? Or maybe it uses a default layout and the result is not what you want?

Drupal splits the management of content and how it is presented on a page in a very precise way. You can have the same content presented with very different layouts.

The layer of Drupal that manages layout and style is called a theme. The aim of this book is to teach you what the theme layer is, how it works, and how to leverage it to style content the way you want.

To get started, you need an environment where you can do your work. You can choose between your local machine or some remote service; in both cases, you will need a way to run a PHP interpreter, a web server, and a database server.

You will also need a code editor that supports working on different kinds of files—such as PHP, CSS, JavaScript, and YAML—and that is advanced enough to help you navigate through the project, write new code, and debug existing code.

In this chapter, we’ll set up that environment.

We will cover the following topics:

  • Installing the required software
  • Installing the demo site
  • Exploring the demo site
  • Disabling production optimization

Technical requirements

Which software to use to run a project locally can be a matter of taste or a best practice enforced by a team (or an organization). In this section, we’re going to install a selection of software that is free (at least for personal use) and, if possible, open source.

The following selection is not mandatory but it will simplify reading the rest of the book because all the screenshots and examples are based on the platforms mentioned.

Git

Git is a distributed version control system that helps developers manage their source code changes over time. It tracks changes in code and allows multiple developers to collaborate on a project simultaneously. Git allows developers to work on their own copy of the code, experiment with different changes, and merge those changes back into the main code base when they're ready. It also allows for backup and recovery of code in case of system crashes or data loss. Git is widely used in software development and other collaborative projects.

The code used in this book is hosted in a Git repository provided by a company called GitHub. From that remote repository, you can obtain (clone) a copy of the code. A Git client is available by default on Linux and macOS systems; on Windows, you must use the WSL 2 subsystem.

You usually interact with Git using the command line, but different tools exist to provide a graphical user interface (one of these is Visual Studio Code, which we’ll install later).

Docker

Docker is a technology used to replicate the same software stack everywhere, independently of the host operating system. This is mandatory to keep consistency between all the developers in a team who may individually use different operating systems. Docker is also useful for replicating as much as possible the configuration of the production environment or having multiple stacks on the same local machine, each one with different software versions and configurations. Maybe you’re working on an old Drupal 7 website that requires PHP 7.*, and a shiny new Drupal 10 website that requires PHP 8.1.

Docker can be installed in different ways, but here we’ll use the simplest one: Docker Desktop.

Docker Desktop is a commercial application developed by the Docker team itself and it’s free for use unless you’re in a large enterprise (more than 250 employees or more than 10 million USD in annual revenue) or some government entity.

Detailed instructions on how to install it can be found at https://docs.docker.com/get-docker/. In the next examples, we’ll use macOS, but the setup and usage are the same on Windows and Linux.

After the installation, you may need to set up Docker Desktop to match your system. Here’s how to do that:

  1. To run Docker, simply click on its icon in the applications list. Once it's up and running, you'll see the Docker icon appear on the top right of your screen. Clicking on the icon will open a menu where you can easily check if Docker Desktop is running smoothly or if there are any issues to address.
Figure 1.1 – Docker Desktop menu

Figure 1.1 – Docker Desktop menu

  1. Click on the Preferences link to open the Preferences window.
  2. Click on the Resources | Advanced section to tweak how many of your system resources Docker can consume. On the right pane, you can select how many CPUs and how much memory, swap, and disk size Docker can use:
Figure 1.2 – The Advanced section of Docker Desktop

Figure 1.2 – The Advanced section of Docker Desktop

In this case, I’ve set my system to grant Docker up to 4 CPUs and 12 GB of memory. Usually, you’ll want to choose half of the resources of your system.

  1. Click on the Resource | File sharing section to configure which directories can be bind-mounted into Docker containers:
Figure 1.3 – The File sharing section of Docker Desktop

Figure 1.3 – The File sharing section of Docker Desktop

In a production environment, you will have a Docker image that contains both the PHP interpreter and the code of the website, but in a local environment, to speed things up, the code stays on the host (your local machine) and is then mounted (made accessible) to the Docker container using a volume. Docker Desktop allows only for a subset of your computer filesystem to be mounted to a Docker container (for security and performance); you can set which directory to include in the File sharing section of the Preferences pane. The /Users directory is included by default, so you can just clone the demo repository somewhere inside this folder.

To be sure everything is clear, here you can find a list of base Docker concepts as a reference:

  • Docker engine: The core system that allows you to build and run containers.
  • Image: Contains a list of instructions used to build a container.
  • Container: This is the executable image that contains everything needed to run an application.
  • Volume: This is the system used by Docker to persist a container’s data between executions. So, container data stored in a volume will be preserved even if the container itself is stopped or removed. Furthermore, the same volume can be attached to multiple containers.
  • Compose: This is a tool that allows a set of containers to work together in the same network.

To run a Drupal website, we need at least two containers—one with a web server and one with a database server. Other containers can be useful during development, such as one to explore the database data and one to catch sent emails (for debugging purposes).

Of course, you can set up your stack from scratch, choose which images to use (or build some custom ones), configure them, find a way to orchestrate them, and so on. Because this is a book on Drupal and not Docker, we’ll use a tool that does everything we need for free.

DDEV

DDEV is an open source tool to speed up local PHP development. It uses Docker to configure and run everything that is required to work on a Drupal (or other PHP-based) website. It also provides a lot of commands to interact with the stack.

DDEV configurations can be added to Git and shared with all developers in the team. In this way, whoever clones and spins up the project will have exactly the same environment.

Again, the installation procedure depends on your computer's operating system. You can find all the details on the project website: https://ddev.readthedocs.io.

Note

Pay attention to the installation procedure—one required step is about installing and configuring mkcert (https://github.com/FiloSottile/mkcert). mkcert allows you to visit any DDEV-managed website using HTTPS just as it will be in production.

DDEV doesn’t have a graphical interface; everything is managed through the command line. To see a list of all available DDEV commands, you can simply type ddev on your terminal:

ddev

The demo code you’ll download in the next section contains a ready-to-use DDEV setup, located in the .ddev folder in the root of the repository.

Visual Studio Code

More than just a code editor, we need a full IDE to support our work with different kinds of files. Here, we have a lot of choices, which are mainly driven by personal taste and budget. One IDE that is free but very powerful is Visual Studio Code.

Visual Studio Code is a free application that runs nearly everywhere, from every operating system through the web (it’s the IDE that powers https://github.dev and https://www.gitpod.io, for example).

Note

You can find detailed instructions about how to download and install Visual Studio Code at https://code.visualstudio.com/docs.

Visual Studio Code's features can be enriched by installing extensions; we’ll need some of them to speed up our work, including the following:

  • PHP Intelephense
  • PHP Debug
  • Tailwind CSS IntelliSense
  • Twig Language 2
  • Prettier (a code formatter)

To install an extension, follow these steps:

  1. Open Visual Studio Code.
  2. Click on the View | Extensions menu item to open the extensions view.
  3. Use the search engine to find the extension to add.
  4. Click on the Install button under the extension name in the right pane:
Figure 1.4 – PHP Intelephense is one of the most complete plugins for working on PHP with Visual Studio Code

Figure 1.4 – PHP Intelephense is one of the most complete plugins for working on PHP with Visual Studio Code

Our local stack is ready to be used. In the next section, we’ll use it to set up and run the demo website.

Installing the demo site

Now that the local environment is ready, we can clone the repository of the demo site.

Cloning and building

The repository has two branches, one with the final website (the same one that you will have at the end of this book) and one with just the CMS configured. We’ll start with the latter, but if you want to see the final result you can switch to the first one.

Start by cloning the repository in a local folder. Remember that Docker Desktop limits the folder that can be mounted in a container, so choose one that is included (usually a subfolder of your home directory is the safer choice):

git clone https://github.com/PacktPublishing/Modernizing-Drupal-10-Theme-Development

Then, cd to that folder and start the DDEV stack:

ddev start

This command starts the stack but doesn’t build the website; to do that, you must run this command:

ddev build

build is a custom command, not part of the original DDEV installation, and it’s available because it has been defined in the .ddev/commands/web folder of the repository you’ve cloned. In the .ddev/commands folder, you will find some other custom commands that we have added to DDEV, and you can add your own too. Commands are bash scripts that run on your host shell or in one of the running containers, depending on which folder contains it:

  • .ddev/commands/host: The host computer
  • .ddev/commands/web: The web container (where the web server and the PHP interpreter run)
  • .ddev/commands/db: The container that runs MySQL

Note

The folder that contains the website is mounted into the web container. The files are exactly the same, but they can be accessed from your local computer and from the web container. Bear in mind that the absolute path may be different between the two systems. On your local computer, it will be something such as /Users/lussoluca/Sites/modern_drupal_themes, but on the web container, it will always be /var/www/html. You can connect to a shell that runs in the web container using the ddev ssh command. To close the web container shell and return to the host shell, just type exit and hit Return.

Internally, the build command uses a set of tools to download all the required dependencies and install the website.

Every time you want to reinstall the demo website from scratch, you can execute the build command again.

DDEV provides some other useful commands, as follows:

  • stop: Stop and remove the containers of a project. Does not lose or harm anything.
  • describe: Get a detailed description of a running DDEV project.
  • delete: Remove all project information (including the database) for an existing project.

And there are many more—just type ddev and hit Enter to see them all.

Note

During the start process, DDEV may print a message such as “ssh-agent container is running: If you want to add authentication to the ssh-agent container, run 'ddev auth ssh' to enable your keys.” You can safely ignore this warning in our context.

Composer

All the external PHP dependencies needed to run the website (such as contrib modules and development tools) are not versioned in the Git repository. Instead, they’re downloaded from the internet using a tool called Composer. Composer manages packages using a Semantic Versioning approach, where every package has a version in the form of major.minor.patch (more information at https://semver.org). The application and its dependencies are described in a file called composer.json, usually located in the root folder of the project. Composer has a lot of commands, but the three most used are shown next.

Here’s the first one:

composer update –prefer-dist

This updates all the packages to the latest version (always respecting the Semantic Versioning rules). This command also updates (or creates) a composer.lock file that stores the exact version that has been installed for each package. The composer.lock file must be added to the Git repository and is mandatory to allow every developer on the team, the CI/CD pipelines, and remote environments to have the same version of every dependency.

The second most used Composer command is this one:

composer install –prefer-dist

This reads from a composer.lock file and downloads the exact version of every package.

Finally, when you need a new package (for example, the WebProfiler contributed module) you can run the following command:

composer require drupal/webprofiler

The ddev build command already executes composer install for you, and you can see the list of required packages in the composer.json file in the root folder of the project.

Configuration management

Starting from Drupal 8, the system exports all the configuration needed to recreate the site into a folder, where each configuration is stored as a YAML file. A complex website can have hundreds of such files. Drupal doesn’t use those files directly; they must be imported into the database (this means that if you change one of those files manually, it needs to be imported again to be seen by Drupal). A way to package configurations is to create an installation profile. Drupal core has some ready-to-use installation profiles, such as Standard, Minimal, and Umami (you can see the full list by installing Drupal using the web interface or by looking in the core/profiles folder). In our demo website, we have defined a new installation profile, called AlpsTrips, in the web/profiles folder.

Just about everything in Drupal has a double name—one for humans (such as the profile name, AlpsTrips) and one for machines (that has more restrictive rules, such as no spaces, only some special characters allowed, and so on). The machine name for the AlpsTrips profile is alps_trips_profile.

Drush

One of the packages downloaded by Composer is Drush (https://www.drush.org/latest/). Drush is not a Drupal module and it isn’t used by the website itself; it’s used to automate operations on a Drupal website from the command line. Tasks such as installing Drupal, managing content or users, installing modules, and so on can all be done without even opening a browser instance. To see all the available Drush commands, you can run the following:

ddev drush

DDEV will forward the call to the Drush instance present in the web container.

Default Content

The content of a Drupal website stored in the same database that is used for configurations, but unlike configurations, the core of Drupal doesn’t have any tools for exporting them. To style the website, we need some content to work on (but also for showing the work in progress to the customer, or for writing end-to-end tests). This can be done in a lot of different ways; the community has not yet agreed on the tool to be used by default.

One solution is to use the Default Content contributed module (https://www.drupal.org/project/default_content).

On the demo website repository, we've used Default Content to export a set of dummy contents to a custom module (located on the web/modules/custom/demo folder). When this module is enabled, the contents are automatically imported into Drupal.

Yarn

The latest tool that is used to build our website is Yarn. Yarn is a package manager for Node.js, and we need it for the same reason we need Composer for PHP packages: we don’t want to save the dependencies in our repository. Similar to Composer, Yarn uses two files—package.json and yarn.lock—to describe which packages to download and at which exact version. Yarn can also be used to define and run custom scripts, such as building CSS and JavaScript assets.

All of those tools are used by our build command to go from a set of files in a repository up to a fully functional Drupal website. The tasks that are executed are set out here:

  1. Use Composer to download all the required PHP dependencies: composer install –prefer-dist.
  2. Use Drush to install Drupal from a set of configurations.
  3. Use the Default Content module to import dummy content.
  4. Use Yarn to download all the required JavaScript dependencies and to build the theme assets.

After the build command ends, you can open a browser and start navigating. The website URL is printed at the end of the ddev start command. At any time, you can use the ddev describe command to print a list of details about the project. The URL you’re looking for is the one for the web service:

Figure 1.5 – Using ddev describe to list all the available services for a project

Figure 1.5 – Using ddev describe to list all the available services for a project

In this case (and probably also for you), the URL is https://packt.ddev.site, and the website should look like this:

Figure 1.6 – The home page of the AlpsTrips website

Figure 1.6 – The home page of the AlpsTrips website

You’re navigating as an anonymous user; if you want to administer the site, you must log in as a user with some administrative privileges. During the build, one such user has been created for you, with admin as username and admin as password. To log in, you can do the following:

After submitting the credentials, you should see some more elements, such as a dark toolbar at the top of every page. From there, you can access every configuration page of Drupal.

Note

The admin user created during the installation phase of Drupal has too much power. The permissions enforcement and the access checks don’t run for that user. In a real project, we suggest you create a new user, with only the permissions required.

The demo website is packed with everything you will encounter in a standard Drupal website, so let’s explore it and review all the concepts we’ll need to style it.

Exploring the demo site

Frontend development in Drupal usually starts very late in a project life cycle.

The typical steps are reproduced here:

  1. The design team has to create mockups, style guides, and the design system.
  2. The backend team has to set up the stack, initialize the project, and build the content structure.
  3. Some content needs to be created (manually or with some automatic process).
  4. Finally, the frontend team works on the frontend.

The main focus of this book is on the last step.

We could try to teach you how the theme layer of Drupal works in an abstract way, without implementing any real theme, or we could start from the first step in the list and make you do a lot of stuff even before you start to understand what a theme is.

We don't think this is the best thing we can do. Instead, we’ll take a little bit of an opinionated approach.

By simulating what happens in a typical project, we have already followed the first three steps for you.

We have implemented a fully configured Drupal 10 website, with a content structure and some example content. We’ve added some other modules that are quite standard in a modern Drupal website, such as Paragraphs (https://www.drupal.org/project/paragraphs).

We have created a design system (https://en.wikipedia.org/wiki/Design_system) and a style guide (https://en.wikipedia.org/wiki/Style_guide).

We’ve also defined how the project should run on your local machine. We’ve chosen for you where the code is hosted, the rules to enforce code quality, and the tools to use.

The demo website has enough features to let us talk about every aspect of the theme layer of Drupal 10, but it’s simple enough to avoid wasting time doing the same thing twice. We have a home page, some listing pages, a detail page, and some forms.

We’ve made a lot of assumptions to allow you to concentrate on the frontend layer only. But don’t worry—we’ll explain every decision we’ve made.

Because of this, the code in the book is not enough to replicate the demo website, so you have to start by cloning the Git repository from GitHub (https://github.com/PacktPublishing/Modernizing-Drupal-10-Theme-Development). We suggest you follow along with the explanations by trying them on your local computer—we’ll guide you step by step.

Let’s start by reviewing how editorial data is managed by Drupal and which concepts we’ll use during the rest of the book.

Fields

All information an editor writes in content using the Drupal admin interface is stored in fields. A field can have different properties, widgets, and formatters. Let’s look at these in a bit more detail:

  • Property: Represents the data stored in the database—for example, a text area field has three properties: value, summary, and text format; a geographical field that represents a point on a map probably will have two properties: the latitude and the longitude.
  • Widget: An element used by an editor to insert data into the field—for example, a <textarea> HTML element for a text area, or two text fields for a geographical point (to input the latitude and the longitude).
  • Formatter: The markup used to show the field value on the frontend so that a user can read it—for example, a formatter for a text area can simply render the text, maybe truncated, whereas a geographical field can be rendered like a marker on a map.

Note

A single field type can have more than one supported widget and more than one supported formatter.

Paragraph types

A paragraph is not a concept that comes from the core of Drupal; it’s contributed by an external module called Paragraphs (https://www.drupal.org/project/paragraphs).

Modern layouts are built by aggregating components, and one possible way to manage such components in Drupal is by using the Paragraphs module.

Paragraphs are a collection of fields that together build a component. For example, a hero paragraph can be made of a background image, a claim, and a CTA button (composed of a label and a URL). A slider paragraph can contain a media field where the editor can insert a list of images to show in a carousel…. and so on.

You can define as many paragraph types as you need to allow editors to compose complex pages.

Content types

Fields and paragraphs are then aggregated into content types. A content type is a collection of fields, such as a paragraph, but with some added features. For example, all content built from a content type has a canonical URL so that it can be added to a menu and navigated by the end user.

Content types are used to represent the different structures an editor can insert into a website, such as a blog post, a landing page, a news page, and so on.

An instance of a content type is called a node.

Vocabulary

Often, it is useful to tag or categorize content, to add information to the end user or for it to be aggregated in some way.

For example, on the demo website, the Trip content type can be tagged by difficulty or by trip duration. To manage this kind of functionality, Drupal provides a taxonomy system, which allows you to manage the vocabulary of terms.

Blocks

Content types (and paragraphs) are not the only way to add editorial content to a website; the block system allows you to put contextual information around the main content—for example, on the header, the footer, or in a sidebar. Blocks are useful because they aren’t related to a specific URL, but they’re shown on a page based on a set of visibility rules. For example, you can place a block on the sidebar of every node of a particular content type, or for every user in a role.

Views

Content is usually aggregated in lists—for example, the latest blog posts or the trips available in a specific season. On a Drupal website, every time you mention a list of something, you’re talking about a view. A view is a collection of elements, extracted from the database using a set of conditions. A view’s output can then be shown at a specific URL or in a block.

Menus

In the end, a website is made of pages that can be navigated by the final user. Pages in Drupal are a mix of nodes, views, and blocks, and the navigation is managed by the menu system. A menu in Drupal is a hierarchical structure that stores a navigation tree. Every element in the tree has a label and a URL, which can be internal or external. A website can have more than one menu—maybe one for the main navigation, one with the user links, one for the footer, and so on.

Before starting to work on the design, we need to do just one more step: disable all the performance optimization that Drupal has out of the box.

Disabling production optimization

Starting from version 8, Drupal is optimized for production out of the box. This means that all cache layers are enabled, and a change in the code is probably not visible until the cache is cleared. Obviously, this can slow down development a lot. In the earlier phases of development, all those optimizations can be turned off, but it is mandatory to turn them all back on before production because running a Drupal site without the cache enabled can hide some very difficult-to-catch bugs. How many times have you heard of data breaches where a legit logged-in user had access to data about some other user? This is probably a cache issue, where a page has been built for a user and then cached and served as is to every other user. If that page contains some personal data, that is leaked to everyone.

Note

Drupal is a complex system; to build a single page, it needs to do a lot of things, and most of them involve some sort of interaction with an external (and usually slow) system (the database for the data, the filesystem for the code, and others). If the markup that Drupal is building can be used as is for multiple requests, it’s a waste of resources to build it over and over again. Cache systems exist precisely to store the intermediate steps of a complex calculation to avoid doing the same thing twice. This text is not part of the note. It must be moved outside, just before the next sentence (At the end...)

At the end of the web/sites/default/settings.php file, we’ve added these lines:

if (
  file_exists($app_root . '/' . $site_path . '/settings.local.php')
  && getenv('IS_DDEV_PROJECT') == 'true'
  )
{
  include $app_root . '/' . $site_path . '/settings.local.php';
}

This basically means that if some conditions are true, the system should include a configuration file with local settings. The conditions are set out here:

  • Check whether the $app_root . '/' . $site_path . '/settings.local.php' file exists. app_root resolves to the /var/www/html/web folder, and site_path resolves to the sites/default folder
  • Check whether the value of the IS_DDEV_PROJECT environment variable is true

Both conditions are true on our local stack; the file it’s located at /var/www/html/web/sites/default/settings.local.php and its content has been copied from /var/www/html/web/sites/example.settings.local.php, with a couple of lines uncommented. Let’s see the most important ones:

$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';

Drupal organizes all the business logic into services, discrete PHP classes that perform a specific task (such as sending an email, rendering a template, writing to logs, and so on). All those services are managed by a service container (https://symfony.com/doc/current/service_container.html). When some code needs a service to perform a task, it asks the service container to provide one, along with all its dependencies. The service container also manages parameters, which are scalar values that can be used to configure the application.

One of the services defined in the service container manages the integration with a cache backend.

A cache backend is used to store data that is slow to be computed. Instead of executing the same slow code on every request, Drupal can store the results in a cache. This speeds up the building and delivery of pages.

By default, the cache backend is the same database that Drupal uses for content (managed by a service called cache.backend.database). Every time Drupal needs to save some intermediate computation, it passes the data to the cache system, which in turn uses the cache backend to persist it somewhere.

We can use the development.services.yml file to add or change services and parameters in the service container. Let’s break down the file to see what it does:

parameters:
  http.response.debug_cacheability_headers: true

This parameter forces Drupal to add a couple of HTTP headers to the response. This will be useful later when we talk about cache tags.

twig.config:
  debug: true
  cache: false

Those two lines configure Twig (Twig is the render engine that turns templates and data into HTML), by enabling debug and disabling the cache.

services:
  cache.backend.null:
  class: Drupal\Core\Cache\NullBackendFactory

Lastly, here we define a new cache backend service, cache.backend.null, which uses the NullBackendFactory class to manage the cache. NullBackendFactory doesn’t persist the cache anywhere, basically forcing Drupal to rebuild its data structures on every request.

Continuing with the settings.local.php file, we find the following:

$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;

Those two lines disable the CSS and JavaScript preprocessing and minification system of Drupal. When preprocessing is TRUE, if you look at the source of any Drupal page, you will see something like this:

<link rel="stylesheet" media="all" href="/sites/default/files/css/css_4X4pNrCAbSu81rOnCPB9UMoipKt5NIfi5kpoa86bdG8.css" />
<link rel="stylesheet" media="all" href="/sites/default/files/css/css__4bA7B8aKHQdv-woFVLAGpXcUrTGif-jwiZJPj5yZ1s.css" />
<script src="/sites/default/files/js/js_Y151moVVESM9BeoCt8M3cSJ2_x_o14H43dXy6nGL6JM.js"></script>

This is difficult to understand because isn’t clear where a CSS rule or a JavaScript function comes from (also because the CSS in those files are minified). When preprocessing is FALSE, the output is way more readable:

<link rel="stylesheet" media="all" href="/core/themes/stable9/css/system/components/ajax-progress.module.css?rmstqh" />
<link rel="stylesheet" media="all" href="/core/themes/stable9/css/system/components/align.module.css?rmstqh" />
<link rel="stylesheet" media="all" href="/core/themes/stable9/css/system/components/autocomplete-loading.module.css?rmstqh" />

In the preprocessed version, the filename changes every time the cache is cleared, and this forces the browser to download the file again. When preprocessing is turned off, Drupal emits the original name of the file. To force the browser to download the file again, a token is appended at the end.

Three more lines deserve attention in settings.local.php:

$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['page'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

Those lines are commented in the original example.settings.local.php file. By removing the comments, we force the cache bins that deal with HTML generation to use the cache.backend.null service that we added in the default.services.yml file.

Note

Starting from Drupal 10.1 there is an easier way to manage development settings. A new Configuration | Development settings page has been added that allows you to turn on Twig development mode and to turn off render cache, dynamic page cache, and page cache. You can find more information on the related change record here: https://www.drupal.org/node/3359728.

Enabling Twig debug and disabling caches slow down the website but will allow us to see a change in template as soon as we reload a page, without the need to clear the cache. As we mentioned before, the functionalities of the website must be tested with those caches enabled, as they will be in production, to avoid possible data leaks.

Summary

In this chapter, we learned an easy way to set up a local machine to work on a Drupal 10 website. Using Docker and DDEV, we installed the website we’ll work on for the rest of the book. We also installed and set up an IDE, Visual Studio Code, which will allow us to inspect and work on the code in a powerful way. We dissected the demo website to recap how a Drupal website is made and which concepts we need to understand it. Finally, we disabled all the performance optimization to speed up the development of the new custom theme.

It's time to start building our theme. In Chapter 2, Setting a New Theme and Build Process, we'll create a new theme from scratch and set up a build process to automate some useful tasks.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore real-world examples with proven methodologies to gain a deeper insight into the Drupal theme layer
  • Learn how to translate a graphic design into a maintainable and robust Drupal theme
  • Improve performance and accessibility with a decoupled frontend to consume data exposed by Drupal’s APIs
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Working with themes in Drupal can be challenging, given the number of layers and APIs involved. Modernizing Drupal 10 Theme Development helps you explore the new Drupal 10’s theme layer in depth. With a fully implemented Drupal website on the one hand and a set of Storybook components on the other, you’ll begin by learning to create a theme from scratch to match the desired final layout. Once you’ve set up a local environment, you’ll get familiarized with design systems and learn how to map them to the structures of a Drupal website. Next, you’ll bootstrap your new theme and optimize Drupal’s productivity using tools such as webpack, Tailwind CSS, and Browsersync. As you advance, you’ll delve into all the theme layers in a step-by-step way, starting from how Drupal builds an HTML page to where the template files are and how to add custom CSS and JavaScript. You’ll also discover how to leverage all the Drupal APIs to implement robust and maintainable themes without reinventing the wheel, but by following best practices and methodologies. Toward the end, you’ll find out how to build a fully decoupled website using json:api and Next.js. By the end of this book, you’ll be able to confidently build custom Drupal themes to deliver state-of-the-art websites and keep ahead of the competition in the modern frontend world.

Who is this book for?

If you are a Drupal backend developer or frontend developer who wants to create Drupal themes that follow industry best practices and are fast and maintainable, this book is for you. Basic knowledge of HTML, CSS, and JavaScript and working knowledge of a CMS are needed to grasp the concepts present in this book.

What you will learn

  • Map design systems made by Storybook components to Drupal structures
  • Understand and use render arrays and Twig templates
  • Get familiarized with the new Single Directory Component feature introduced in Drupal 10.1
  • Define, import, and use CSS and JavaScript libraries
  • Discover how to style content created with fields and paragraphs
  • Define, place, customize, and style blocks
  • Explore advanced topics like extending Twig, making a theme configurable, and boosting performance and accessibility
  • Find out how to build a decoupled website using json:api and Next.js
Estimated delivery fee Deliver to Cyprus

Premium delivery 7 - 10 business days

€32.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 31, 2023
Length: 360 pages
Edition : 1st
Language : English
ISBN-13 : 9781803238098
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Cyprus

Premium delivery 7 - 10 business days

€32.95
(Includes tracking information)

Product Details

Publication date : Aug 31, 2023
Length: 360 pages
Edition : 1st
Language : English
ISBN-13 : 9781803238098
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 101.97
Drupal 10 Module Development
€33.99
Drupal 10 Development Cookbook
€37.99
Modernizing Drupal 10 Theme Development
€29.99
Total 101.97 Stars icon
Banner background image

Table of Contents

20 Chapters
Part 1 – Styling Drupal Chevron down icon Chevron up icon
Chapter 1: Setting up a Local Environment Chevron down icon Chevron up icon
Chapter 2: Setting a New Theme and Build Process Chevron down icon Chevron up icon
Chapter 3: How Drupal Renders an HTML Page Chevron down icon Chevron up icon
Chapter 4: Mapping the Design to Drupal Components Chevron down icon Chevron up icon
Chapter 5: Styling the Header and the Footer Chevron down icon Chevron up icon
Chapter 6: Styling the Content Chevron down icon Chevron up icon
Chapter 7: Styling Forms Chevron down icon Chevron up icon
Chapter 8: Styling Views Chevron down icon Chevron up icon
Chapter 9: Styling Blocks Chevron down icon Chevron up icon
Chapter 10: Styling the Maintenance, Taxonomy, Search Results, and 403/404 Pages Chevron down icon Chevron up icon
Part 2 – Advanced Topics Chevron down icon Chevron up icon
Chapter 11: Single Directory Components Chevron down icon Chevron up icon
Chapter 12: Creating Custom Twig Functions and Filters Chevron down icon Chevron up icon
Chapter 13: Making a Theme Configurable Chevron down icon Chevron up icon
Chapter 14: Improving Performance and Accessibility Chevron down icon Chevron up icon
Part 3 – Decoupled Architectures Chevron down icon Chevron up icon
Chapter 15: Building a Decoupled Frontend Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(19 Ratings)
5 star 63.2%
4 star 15.8%
3 star 0%
2 star 5.3%
1 star 15.8%
Filter icon Filter
Top Reviews

Filter reviews by




Matt Glaman Sep 26, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Don't let the title make you think it is about theme development. The book provides excellent coverage of general Drupal knowledge, so much so that I highly recommend this book as a go-to resource for any frontend or full-stack developer new to Drupal. I recommend it for any backend developer working on a large team so that they understand the work their frontend colleagues are performing and how to assist them best.I enjoyed the flow of the chapters. Reading this book made me think back to when I had my first job building websites, which was primarily front-end development. The book takes you down the journey of a developer tasked to implement a design onto a Drupal site.There is a starting code base that you clone down and work with throughout the book. This felt natural for how build phases may work: backend developers or site builders scaffold the site, and then it is themed.The book begins with onboarding the reader to create a local environment, using the demo code base, some basics of how Drupal works, and how to create a new theme. Then, it dives into styling individual landing pages and components—each step along the way, the book layers in more Drupal knowledge alongside theming implementation.
Amazon Verified review Amazon
Jamie V. Feb 23, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I'm not sure I was expecting as much from this book as I'm discovering it has to offer. I'm more of a backend guy but this book has me absorbed. It takes you from the basics of installing the site to configuring it for local development to summarizing available theme options, and then helping you become a well rounded themer. Very glad I got this book.
Amazon Verified review Amazon
doug vann Oct 04, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
tldr; No matter your current experience with Drupal Theming, after going through the straight-forward examples, you will be a confident Drupal Themer!The opening line of the Preface is brutally honest, "Working with themes in Drupal is not an easy task, and it is typical to get lost digging through all the layers and APIs involved."This is especially true for those like me who never did take the time to fully understand Drupal Theming once we switched to TWIG. I have a lot to learn!I found the language and pace of the book to be excellent and the instructions very thorough and contextualized. Following along is quite smooth. The extra bits of relevant facts is always appreciated!The 1st chapter is a truly helpful explanation on setting up DDEV with the book's Demo Site. This is SO VALUABLE! Following along with a real site is absolutely essential for understanding these concepts.After that you are on the open road to understanding Drupal 10 Theming by starting to build your own Bootstrap3 based theme.The "Building a Decoupled Frontend" chapter was especially valuable to me. As in all preceding chapters, the instructions to DIY are pleasantly detailed and include side-bar nice-to-knows to represent when the scope of the current action could be different under dynamic circumstances.
Amazon Verified review Amazon
Jason Bugiada Oct 23, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book begins by introducing the concept of design systems and explaining how to map them to the structures of a Drupal website. It then covers all aspects of Drupal theme development, from creating a theme from scratch to theming blocks, fields, and paragraphs. The book also includes chapters on advanced topics such as extending Twig, making a theme configurable, boosting performance and accessibility, decoupled theming, and integration with Storybook.A few things I like about the book:The author walks you through the setup of a local development environment using DDEV. He walks you through creating a new theme with Starterkit. The author gets in detail on how Drupal renders an HTML page. He also walks you through setting up Single Directory Components and how to map them to storybook.Overall, I highly recommend Modernizing Drupal 10 Theme Development to anyone who wants to learn how to build modern Drupal themes.
Amazon Verified review Amazon
Pooja Pundir Oct 06, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I recently started reading this book, and although I haven't finished it yet, I wanted to share my initial impressions. The book starts with setting up a local environment using DDEV, which is quite unique in the sense that I see it mostly at the end in other books. This is quite useful when you want to gain practical experience from day one. Based on my reading so far, it seems that this book is useful for all types of Drupal developers. It covers all aspects of Drupal and is not limited to just theme development.However, this may seem confusing to those who have no prior experience with Drupal development. Overall, it's a great book. Kudos to its author.I plan to continue reading and will update my review after I finish the book.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela