Drupal Theming: An Introduction to Twig and Creating Custom Themes

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.

1. Twig Basics

What is Twig?

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.

How Twig Works in Drupal

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.

Basic Twig 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 %}' %}
    

Benefits of Twig

2. Setting Up a Custom Theme

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.

Step 1: Create the Theme Directory

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
    

Step 2: Create info.yml File

Inside 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'
    

Step 3: Add CSS and JavaScript Files

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.

Step 4: Create Base Template Files

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>
    

Step 5: Enable the Theme

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
    

3. Best Practices in Theming

When theming in Drupal, it's important to follow best practices for consistency, maintainability, and performance. Here are some crucial tips:

Template Hierarchy

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.

Naming Conventions

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

Overriding Templates

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
    

4. Responsive Design

Ensuring your theme is mobile-friendly is critical. Responsive design ensures that your website looks good on all devices, including desktops, tablets, and smartphones.

Mobile-First CSS

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;
}
    

Responsive Images

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" />
    

Benefits of Responsive Design

5. Preprocessing Functions

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.

What is a Preprocess Function?

Preprocess functions are PHP functions that prepare variables for use in Twig templates. They follow the naming convention template_preprocess_HOOK.

Example: Preprocessing Node Content

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';
}
    

Benefits of Preprocessing

Conclusion

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

Card Image

How to Set Up a Local SSL Certificate on Apache: Step-by-Step Guide

Learn how to set up a local SSL certificate on Apache with this comprehensive step-by-step guide. Secure your local development environment with HTTPS.

Card Image

Latest Features of Coding Technology

Explore the latest features and advancements in coding technology, including new programming languages, frameworks, DevOps tools, AI integration, and more.

Card Image

Understanding Laravel Mix Webpack Configuration: Step-by-Step Guide

Step-by-step explanation of a Laravel Mix Webpack configuration file, including asset management for JavaScript, CSS, and Vue.js support.

Card Image

How Emojis Can Enhance Your Git Commits | Gitmoji Guide

Discover how to enhance your Git commits with emojis. Learn about the best practices for creating informative and visually distinctive commit messages.