Drupal Theming: An Introduction to Twig and Creating Custom Themes
Drupal theming offers developers complete control over the design and presentation of their websites. With the introduction of Twig, the powerful templating engine in Drupal 8 and beyond, theming has become more secure and efficient. This guide provides an in-depth look at Twig basics, how to set up custom themes, and the best practices for structuring templates. Additionally, it covers creating responsive designs to ensure your site is mobile-friendly and leveraging preprocessing functions to manage data effectively before rendering, providing flexibility and customization in the theming process.
Twig is a modern PHP-based templating engine that is used in Drupal 8 and later versions to handle the presentation layer. It replaces PHPTemplate, which was used in earlier versions of Drupal. Twig is more secure, flexible, and easier to read than its predecessor. It separates the logic from the presentation, providing a clean and maintainable code structure.
Twig templates are used to display the content of your Drupal site. Each page in Drupal consists of various pieces, such as nodes, blocks, and regions, all of which are rendered using Twig. Twig files are typically found in .html.twig
format and can contain HTML along with Twig-specific syntax.
Here's a simple example of Twig syntax for outputting a variable:
{{ '{{ content.title }}' }}
In this example, {{ '{{ content.title }}' }}
outputs the title of a node. Twig tags and filters also allow for more dynamic content rendering:
{% '{% if content.body %}' %}
<div class="node-body">{{ '{{ content.body }}' }}</div>
{% '{% endif %}' %}
Building a custom theme allows you to fully control the design of your Drupal website. Here’s a step-by-step guide to setting up a basic theme.
Navigate to the themes/custom
directory in your Drupal installation and create a new folder for your theme:
cd themes/custom
mkdir my_custom_theme
info.yml
FileInside your theme directory, create a file named my_custom_theme.info.yml
. This file tells Drupal about your theme and provides necessary metadata.
name: 'My Custom Theme'
type: theme
description: 'A custom theme for my Drupal website.'
core_version_requirement: ^8 || ^9
libraries:
- my_custom_theme/global-styling
regions:
header: 'Header'
content: 'Content'
footer: 'Footer'
To define your CSS and JavaScript, create a my_custom_theme.libraries.yml
file:
global-styling:
css:
theme:
css/styles.css: {}
js:
js/scripts.js: {}
Now, create a css
folder and a js
folder in your theme directory, and add styles.css
and scripts.js
files respectively.
To start theming, create a basic page template by adding a page.html.twig
file in the templates
folder:
<!DOCTYPE html>
<html>
<head>
<title>{{ '{{ head_title }}' }}</title>
{{ '{{ page.head }}' }}
{{ '{{ page.styles }}' }}
</head>
<body>
<header>
{{ '{{ page.header }}' }}
</header>
<div class="content">
{{ '{{ page.content }}' }}
</div>
<footer>
{{ '{{ page.footer }}' }}
</footer>
{{ '{{ page.scripts }}' }}
</body>
</html>
Once your files are in place, enable your theme by navigating to Appearance
in the Drupal admin interface or using Drush:
drush theme:enable my_custom_theme
When theming in Drupal, it's important to follow best practices for consistency, maintainability, and performance. Here are some crucial tips:
Drupal uses a template hierarchy to determine which template files should be used to display content. For example, Drupal will first look for a more specific template file before falling back to a more generic one.
node--article.html.twig
for nodes of type article.node.html.twig
for all other node types.Naming convention is important for overriding templates in a structured way. You can create specific templates based on content type, block ID, or views.
Example of a block-specific template:
block--block-id.html.twig
To override a default template, copy the template from the core or base theme, place it in your theme’s templates
folder, and make modifications.
Example of overriding the node template:
cp core/modules/node/templates/node.html.twig themes/custom/my_custom_theme/templates/node.html.twig
Ensuring your theme is mobile-friendly is critical. Responsive design ensures that your website looks good on all devices, including desktops, tablets, and smartphones.
It’s a best practice to write mobile-first CSS. Start with styles that work on small screens and progressively enhance the design for larger screens.
/* Base styles for mobile */
body {
font-size: 16px;
line-height: 1.5;
}
/* Styles for larger screens */
@media (min-width: 768px) {
body {
font-size: 18px;
}
In your theme’s Twig templates, you can use responsive image styles to ensure that images are optimized for different screen sizes:
<img src="{{ '{{ file_url(node.field_image.entity.uri.value) }}' }}" alt="{{ '{{ node.field_image.alt }}' }}" class="responsive-image" />
Preprocessing functions in Drupal allow you to manipulate data before it is passed to Twig templates. This is crucial for adding custom logic to your theming layer without cluttering the template files with PHP code.
Preprocess functions are PHP functions that prepare variables for use in Twig templates. They follow the naming convention template_preprocess_HOOK
.
Here’s an example of a preprocessing function in my_custom_theme.theme
file:
/**
* Implements hook_preprocess_node().
*/
function my_custom_theme_preprocess_node(&$variables) {
// Add a custom class to article nodes.
if ($variables['node']->bundle() == 'article') {
$variables['attributes']['class'][] = 'custom-article-class';
}
// Add a custom field to Twig.
$variables['custom_field'] = 'This is a custom field';
}
Drupal theming with Twig offers a powerful and flexible way to create custom themes that are secure, maintainable, and performant. By mastering Twig basics, setting up custom themes, and following best practices, you can build robust Drupal sites tailored to your design vision. Responsive design and preprocessing further enhance the experience by ensuring your site is optimized for all devices and allows for sophisticated content manipulation.
Theming in Drupal is a deep but rewarding process, empowering you to create visually stunning websites with full control over the presentation layer. By following the steps and examples provided, you can get started with building your custom themes today!
Published By: Kartik Sharma
Updated at: 2024-10-08 23:49:10