Reader small image

You're reading from  Modernizing Drupal 10 Theme Development

Product typeBook
Published inAug 2023
PublisherPackt
ISBN-139781803238098
Edition1st Edition
Concepts
Right arrow
Author (1)
Luca Lusso
Luca Lusso
author image
Luca Lusso

Luca Lusso is a Drupal developer with more than 15 years experience, he started with Drupal 5 and PHP 5 in an era where deployments with FTP were still a thing. Since then, he worked as a consultant and contributed to build some of the biggest Drupal websites in Italy. Luca is also a teacher and he has taught Drupal to a lot of different teams, from universities to big system integrators. Luca is an open source lover and Drupal contributor, he maintains some popular modules like WebProfiler and Monolog. He's also a speaker in conferences like DrupalCon Europe and Drupal Developer Days. Lately, he has shifted his interest towards frontend performances. Luca holds a master's degree in Computer Science and he's an Acquia certified developer.
Read more about Luca Lusso

Right arrow

Creating Custom Twig Functions and Filters

Now that the demo website is fully styled, we can move on to some more advanced topics. The first one is the ability to extend Twig with custom functions and filters.

Twig is baked with a highly extensible framework that allows us to do customizations to simplify our templates by delegating the complex logic away from the theme layer.

In this chapter, we’re going to cover the following main topics:

  • Creating a custom Twig function
  • Creating a custom Twig filter

Technical requirements

To run the examples in this chapter, make sure to follow the instructions provided in Chapter 1, Setting Up a Local Environment.

You can find the code for this chapter in the GitHub repository: https://github.com/PacktPublishing/Modernizing-Drupal-10-Theme-Development

Creating a custom Twig function

If you’ve arrived at this chapter after reading the preceding ones, it should be clear that any business logic that doesn’t depend upon a specific layout must not be put in a theme.

Although preprocess functions seem like they would be helpful to alter your data just before it is merged with a template, they have some issues:

  • Tying the business logic to a specific theme will complicate the change to a new theme
  • Altering data that is in a preprocess function can be inefficient because Drupal has already computed the data you’re changing

As we saw in Chapter 9, Styling Blocks, you can use different techniques to extract the fields of an entity:

  • Read field values directly from the entity
  • Use a preprocess function
  • Define a bundle class to expose the entity’s fields

The first two approaches are challenging to be used on different websites. The last one is likely to only be applicable...

Creating a custom Twig filter

Similar to a Twig function used to extract or generate content, a Twig filter can be used to transform a value into something different.

We can use the same WeatherExtension class that we used before to add our custom functions, but this time we’ll implement the getFilters() method:

public function getFilters(): array {
  return [
    new TwigFilter(
      'celsius_to_fahrenheit',
      [$this, 'celsiusToFahrenheit']
    ),
  ];
}

Staying in the field of meteorology, we’ve implemented a Twig filter to convert a temperature value from Celsius to Fahrenheit. The code for the filter is a simple one-line method:

public function celsiusToFahrenheit(
  float $celsius
): float {
  return $celsius * 1.8 + 32;
}

WeatherExtension is already tagged to be a Twig extension (in the...

Summary

In this chapter, we’ve seen how to define new custom functions and filters for Twig, and how to use them in our template.

You also learned about all the functions and filters provided by Drupal core and by some famous contrib modules.

The most important takeaway of this chapter is that you must put the business logic of your Drupal website as far as possible from the theme layer. This is the only way to build a maintainable and future-proof system, where you can switch the frontend theme without affecting the site features and functionality at all. A Drupal theme must only be responsible for taking some data structures (that is, render arrays) and turning them into HTML.

In the next chapter, Chapter 13, Making a Theme Configurable, we’ll talk about how to build a theme that can be adapted to be used on multiple websites, with some little (or big) differences.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Modernizing Drupal 10 Theme Development
Published in: Aug 2023Publisher: PacktISBN-13: 9781803238098
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Luca Lusso

Luca Lusso is a Drupal developer with more than 15 years experience, he started with Drupal 5 and PHP 5 in an era where deployments with FTP were still a thing. Since then, he worked as a consultant and contributed to build some of the biggest Drupal websites in Italy. Luca is also a teacher and he has taught Drupal to a lot of different teams, from universities to big system integrators. Luca is an open source lover and Drupal contributor, he maintains some popular modules like WebProfiler and Monolog. He's also a speaker in conferences like DrupalCon Europe and Drupal Developer Days. Lately, he has shifted his interest towards frontend performances. Luca holds a master's degree in Computer Science and he's an Acquia certified developer.
Read more about Luca Lusso