Drupal Best Practices: Theme Development for Clean, Scalable Sites

Theming is a critical part of Drupal development, transforming your site’s structure and functionality into an engaging user interface. By following theme development best practices, you can ensure that your Drupal site is not only visually appealing but also maintainable, scalable, and easy to update.

In this blog post, we’ll explore essential theme development practices for Drupal:

  1. Use Twig: Drupal 8 and later use Twig as the templating engine. Write clean, efficient Twig templates and avoid using PHP directly in templates.
  2. Component-Based Approach: Organize your theme using a component-based approach, building reusable parts like buttons and cards, ideally with a pattern library such as Pattern Lab.
  3. Use Base Themes: Leverage base themes like Classy, Stable, or Bootstrap to accelerate your theme development and create consistent, maintainable designs.

By incorporating these best practices, you’ll be able to create robust, high-performance themes that are easier to maintain and extend over time.


1. Use Twig for Clean and Efficient Templating

One of the most significant changes introduced in Drupal 8 was the switch from PHPTemplate to Twig as the templating engine. Twig offers a more secure and efficient way of working with templates by discouraging the use of raw PHP in templates and providing a more structured syntax.

Why Twig is Essential for Drupal Templating

  1. Separation of Logic and Presentation: Twig enforces a clear separation between business logic and presentation logic. This ensures that your theme files focus solely on the front-end, while backend processing is handled in the module layer.
  2. Security: With Twig, it's much harder to introduce security vulnerabilities such as cross-site scripting (XSS). Twig automatically escapes output, ensuring that data is properly sanitized before being displayed.
  3. Readability and Maintainability: Twig’s syntax is cleaner and more readable than PHP. It’s easier to understand for both developers and designers, making theme files easier to maintain over time.

Best Practices for Writing Twig Templates

  1. Avoid PHP in Templates: One of the core principles of using Twig in Drupal is to avoid PHP in templates. Twig templates should only be responsible for rendering the data passed to them. All business logic should be handled in preprocess functions or controllers. Example of a clean Twig template for displaying a block:
   <div class="block block--{{ configuration.label }}">
     <h2>{{ label }}</h2>
     <div class="content">
       {{ content }}
     </div>
   </div>

This template only renders the content, leaving logic such as what data to display to the PHP layer.

  1. Use Twig Filters and Functions: Twig offers built-in filters and functions to manipulate data before rendering. For example, you can use the |escape filter to sanitize output, |date to format dates, and |length to count items in an array. Example of using Twig filters:
   <p>{{ node.created|date("F j, Y") }}</p>
   <p>{{ node.body.value|length }} characters</p>
  1. Keep Templates Lean: Don’t overload your templates with too much logic or complex conditionals. Keep them focused on rendering the necessary HTML, while moving any logic into the preprocess functions. Preprocess functions can be defined in your theme_name.theme file, allowing you to manipulate data before it gets to the template. Example of a preprocess function:
   function mytheme_preprocess_node(&$variables) {
     // Add a custom variable for the node author.
     $variables['custom_author'] = $variables['node']->getOwner()->getDisplayName();
   }

In the Twig template, you can simply reference {{ custom_author }} without needing any logic in the template itself.


2. Component-Based Approach for Organized and Scalable Themes

One of the most effective ways to manage complexity in theme development is to adopt a component-based approach. This methodology involves breaking down the theme into reusable components—such as buttons, cards, modals, and forms—that can be assembled to build complex pages. This approach ensures consistency and scalability in your theme.

Why a Component-Based Approach Matters

  1. Reusability: Components are self-contained and can be reused across different parts of the site. For example, a button component defined once can be reused in forms, navigation, and call-to-action sections, ensuring design consistency.
  2. Maintainability: By breaking your theme into components, you make it easier to update and maintain. Changes to a component (e.g., updating the button style) are automatically applied everywhere that component is used.
  3. Scalability: As your site grows, adding new components or modifying existing ones becomes easier. You don’t need to rewrite large chunks of code or update many templates—just update the component in one place.

Using Pattern Lab for Component-Based Theming

Pattern Lab is a tool that works well with Drupal for organizing and managing components. It allows you to create a pattern library, a collection of reusable components that can be referenced throughout the site. These components range from simple atoms like buttons and inputs to more complex organisms like navigation menus and form layouts.

Steps to Implement a Component-Based Approach with Pattern Lab

  1. Install Pattern Lab: Set up Pattern Lab in your Drupal theme to manage your components.
   composer create-project pattern-lab/edition-twig-standard pattern-lab
  1. Organize Components: Define your components in terms of atoms, molecules, organisms, templates, and pages:
  • Atoms: Smallest building blocks, such as buttons, input fields, and labels.
  • Molecules: Groups of atoms functioning together, such as a form field.
  • Organisms: Complex components built from molecules, such as a navigation bar or footer.
  • Templates: Page-level structures that combine organisms.
  • Pages: Specific page instances that apply templates.
  1. Integrate with Twig: Use the same Twig templates in Pattern Lab as you do in your Drupal theme, ensuring that the components you build in Pattern Lab are directly usable in your Drupal site. Example of a reusable button component:
   <button class="button button--{{ button_type }}">{{ button_text }}</button>

This button component can be reused across different templates by passing different variables for button_type and button_text.


3. Use Base Themes for Faster, Consistent Development

Instead of building a Drupal theme from scratch, you can significantly speed up development by using a base theme. Base themes provide a solid foundation with predefined styles, layouts, and components, reducing the amount of custom development needed for common design patterns.

Why Use a Base Theme?

  1. Faster Development: Base themes come with built-in components, layouts, and configurations that speed up the initial setup and development of your theme.
  2. Consistency: Base themes enforce design and development consistency. They provide a standardized way of writing CSS, JavaScript, and templates, ensuring your theme remains maintainable and easy to update.
  3. Customizable: Most base themes are highly customizable, allowing you to extend and override styles and components to suit your project’s needs.

Popular Base Themes for Drupal

  1. Classy: Classy is a base theme that ships with Drupal core. It offers a flexible structure for theme developers who want a starting point without too many predefined styles.
  2. Stable: Stable is a minimalistic base theme that focuses on providing a clean foundation for custom theming. It doesn’t include any CSS, making it perfect for developers who want full control over the design.
  3. Bootstrap: The Bootstrap theme is based on the popular Bootstrap framework, providing a responsive grid system, components, and utilities right out of the box. It’s a great choice for developers who want to leverage the power of Bootstrap for rapid theme development.

How to Use a Base Theme

  1. Install the Base Theme: Use Composer to install a base theme like Bootstrap.
   composer require drupal/bootstrap
  1. Create a Sub-theme: Create a sub-theme based on the base theme. Sub-themes inherit styles and templates from the base theme but allow you to override them as needed. Example of creating a sub-theme for Bootstrap:
  • Copy the Bootstrap sub-theme starter kit from themes/contrib/bootstrap/starterkits to your custom theme directory.
  • Rename the starter kit folder and files, and configure the .info.yml file.
  1. Override Styles and Templates: Override the base theme’s CSS, JavaScript, or Twig templates to customize the design for your site. For example, if you want to customize the navigation menu, you can copy the template file from the base theme and place it in your sub-theme’s templates directory.

Conclusion

Developing a Drupal theme is more than just creating a visually appealing site—it requires a structured, maintainable approach to ensure scalability, performance, and ease of updates. By following these theme development best practices, you can create clean, maintainable themes that are easier to work with over time:

  1. Use Twig for templating to maintain a clean separation between logic and presentation.
  2. Adopt a Component-Based Approach to organize your theme into reusable parts, improving scalability and consistency.
  3. Leverage Base Themes like Classy, Stable, or Bootstrap to jumpstart your theme development and maintain a clean foundation.

By implementing these practices, you’ll build Drupal themes that not only look great but are also maintainable and scalable, ensuring a smoother development process and a higher-quality product.

Do you agree with the content of this article?

You need to join to the Drupal COE to participate, Log In or Claim your profile now.

Did you find this useful?

Would you suggest another article for the Best Practices category?

You need to join to the Drupal COE to participate, Log In or Claim your profile now.