Skip to main content
FreeAn audit of your Drupal siteA written audit of your Drupal site, within three business days
All articles

Backend & EngineeringOct 6, 20269 min read

Theming Drupal without Twig

Valentin ZsigmondFounder & Lead Engineer

Drupal's render pipeline is one of its real strengths. Blocks, regions, preprocess hooks, lazy builders, BigPipe and the render cache work together to build a page, and only at the very end does a template turn variables into markup. sdx_drast keeps all of that and replaces that last step. A theme that declares engine: drast renders every template through React, Vue or Svelte components instead of Twig. The name describes the mechanism: Drupal Render Arrays to Structured Tokens.

This article explains how it works, shows a theme replacing a core template with a React component, and is plain about where Twig still has a role. The examples use sdx_drast 1.0.0-alpha6 and the React base theme sdx_react_base 1.0.0-alpha6.

Why a theme engine and not a module

SDX can already put components on a page from a module: a component render element mounts a React widget inside a Twig theme. That works well for interactive islands. It leaves the rest of the page as it was. Core and contrib output still goes through Twig and reaches the browser as HTML strings, so a component that wants to own a form element, a block or a node has nothing structured to work with.

A theme engine sits at the one point where Drupal hands over the fully preprocessed variables of every template. Replace it, and every template call, from html and page down to a single input, reaches the same code. Everything upstream stays as it is. The engine's own class documentation says it directly: "Only the final template rendering step is replaced."

Theme engines have long been their own extension type, with a .info.yml of type: theme_engine and a procedural .engine file. Since Drupal 11.3, core also loads an engine as a service tagged theme_engine and deprecates .engine files. sdx_drast covers both. The sdx_drast module holds every service, including DrastThemeEngine, registered as theme_engine.drast with that tag. A thin drast engine extension ships with it, and its drast_render_template() forwards to the same service. You install the module; the engine comes with it.

How a render array becomes a component

Take a node teaser. Drupal builds the render array, runs template_preprocess_node() and every module and theme preprocess hook, then calls the engine with the template name and the variables. From there four services take over:

  1. TemplateResolver maps the template name to a component id, such as acme:node.
  2. TemplatePreprocessor pre-renders nested render arrays and resolves the placeholders that Twig output would normally carry, such as Views form items and CSRF tokens.
  3. VariableSerializer turns the variables into JSON-safe props.
  4. RenderContext::pushComponent() encodes the component id and props into a token, which the engine returns in place of HTML.

This is the heart of that path in DrastThemeEngine::renderFrameworkTemplate(), with the debug metadata left out:

protected function renderFrameworkTemplate(string $templateFile, array $variables): MarkupInterface {
  $componentId = $this->templateResolver->resolve($templateFile);

  if ($componentId) {
    $this->templatePreprocessor->preprocess($variables);
    $this->resolveTableHeaders($templateFile, $variables);
    $this->escapeItemListValues($templateFile, $variables);

    $props = $this->variableSerializer->serialize($variables);
    $debug = [];

    $placeholder = $this->renderContext->pushComponent($componentId, $props, $debug);
    return Markup::create($placeholder);
  }

  return $this->renderUnmatchedTemplate($templateFile, $variables);
}

Notice that the engine returns Markup, exactly as a Twig render would. To the rest of Drupal the token is a string, which is why it passes through render arrays, placeholders and caches untouched. When the page template renders, PageRenderer parses the tokens out of every region and replaces them with a tree of component and HTML nodes. That tree goes into the page data JSON, and the client renders it with the registered components. The browser never decodes a token.

Overriding a core template

A DRAST theme is an ordinary Drupal theme with one extra key. This one extends sdx_react_base, which already provides React components for more than fifty core templates:

# themes/custom/acme/acme.info.yml
name: 'Acme'
type: theme
core_version_requirement: ^10.3 || ^11
engine: drast
base theme: sdx_react_base

To replace core's node.html.twig, add a directory named after the template to the theme's templates/ folder, with a file of the same name. The extension follows the framework: .tsx or .jsx for React, .vue, .svelte. No .component.yml is needed.

// themes/custom/acme/templates/node/node.tsx
import React from 'react';
import HtmlFragment from '@sdx/base/HtmlFragment';
import { spreadAttributes } from '@sdx/base/spreadAttributes';
import type { DrupalAttributes } from '@sdx/base/types';

type NodeProps = {
  attributes?: DrupalAttributes;
  title_attributes?: DrupalAttributes;
  url?: string;
  page?: boolean;
  content?: Record<string, unknown>;
  title_text?: string;
  reading_minutes?: number;
};

export default function Node({ attributes, title_attributes, url, page, content, title_text, reading_minutes }: NodeProps) {
  return (
    <article {...spreadAttributes(attributes)}>
      {!page && (
        <h2 {...spreadAttributes(title_attributes)}>
          <a href={url}>{title_text}</a>
        </h2>
      )}
      {reading_minutes ? <p>{reading_minutes} min read</p> : null}
      {content &&
        Object.entries(content).map(([field, value]) =>
          value ? <HtmlFragment key={field} html={value} /> : null,
        )}
    </article>
  );
}

Props carry the template's variable names, the same ones you would print in node.html.twig. spreadAttributes() converts Drupal's attribute map into React props (class to className, a style string to an object). HtmlFragment renders each field whether it arrived as a component tree or as HTML. The last two props do not exist in core; the next section adds them. Run drush sdx:build after adding a component so the bundle includes it.

TemplateResolver looks for node in the active theme first, then in its base themes, so a child theme always wins. Next come the templates/ directories of enabled modules, and last the framework module's base components (sdx_react ships one for node). When Drupal hands the engine a suggestion such as block--system-menu-block, the resolver tries that name first and then strips suffixes down to block. Drupal passes a suggestion's name only when the theme registry has a template for it, as it does for this one, which the System module declares. A component directory does not add a registry entry, so do not expect a suggestion component such as node--article to be picked up on its own. When one component has to vary, branch on props such as view_mode.

Preprocess keeps its job

Preprocess hooks run exactly as before. What changes is what they are for. A Twig template can reach into the node variable and call methods on it. Under DRAST, the serializer deliberately leaves out heavy objects (node, user, comment, taxonomy_term, media, view and a few more) and every key that starts with # or _. Components receive clean data, not Drupal internals, and preprocess is where you choose that data:

<?php

/**
 * @file
 * Theme hooks for Acme.
 */

declare(strict_types=1);

use Drupal\node\NodeInterface;

/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function acme_preprocess_node(array &$variables): void {
  $node = $variables['node'];
  assert($node instanceof NodeInterface);

  // The node object never reaches the component: pass what it needs.
  $variables['title_text'] = $node->label();
  $variables['attributes']['class'][] = 'node--' . $node->bundle();

  if ($node->hasField('body') && !$node->get('body')->isEmpty()) {
    $words = str_word_count(strip_tags((string) $node->get('body')->value));
    $variables['reading_minutes'] = max(1, (int) ceil($words / 200));
  }
}

Inside the page data, the resolved node looks like this (abbreviated; content holds one entry per field):

{
  "type": "component",
  "component": "acme:node",
  "props": {
    "attributes": { "class": "node--article" },
    "title_text": "Spring collection",
    "reading_minutes": 3,
    "url": "/node/12",
    "page": false,
    "view_mode": "teaser"
  },
  "key": "_c0"
}

The class you appended went through Drupal's usual conversion into an Attribute object, and the serializer stored it as a plain map. A scalar added in preprocess becomes a prop of the same name, and contrib preprocess hooks behave the same way. Treat preprocess as the place that shapes a component's API, and keep the component free of Drupal knowledge.

Attributes, cache metadata and accessibility

Attributes. Attribute objects are serialized as name-to-raw-value maps, not HTML-encoded strings, because the client sets them through the DOM. That matters for values such as data-drupal-states, which holds JSON. Everything Drupal puts on an element survives: id, for, role, aria-*, data-*.

Escaping. Drupal's output-trust rules still apply, and under DRAST part of that work moves into your components. A Markup object carries HTML that Drupal has already made safe. A plain string is text that Twig would have escaped. So render plain-string props as text, which JSX does by default, and pass only rendered output to HtmlFragment. Tokens themselves are signed with a site secret, so user text that happens to look like a token is dropped, never rendered.

Cache metadata. Since tokens are strings, the render cache stores them like any HTML. Regions are rendered in isolated render contexts, and PageRenderer collects the cache contexts, tags and max-age that bubble out of them and applies them to the page build. The dynamic page cache therefore varies and invalidates as it would with Twig. Each region also carries a checksum of its cache tags in the page data. On client-side navigation, sdx_router sends those checksums back, and for DataProvider routes the response leaves out every region whose checksum has not changed, so the browser keeps its copy. Template debug annotations, the DRAST counterpart of Twig debug comments, are switched on with sdx_devel's template_debug setting for accounts with access sdx devel, and they add the user.permissions cache context so an annotated render is never served to someone else.

Accessibility. The engine preserves what accessible markup is built from: Drupal's attributes, labels and descriptions as data, and a document shell that keeps the html element's language and direction attributes and a "Skip to main content" link to #main-content. The markup itself is now the component's job. A component that drops title_attributes or turns a button into a div loses what core provided, so accessibility review moves to wherever the markup lives. sdx_react_base gives you a starting point, including the useFocusTrap hook its side panel uses to keep keyboard focus inside an open panel. We wrote about why this deserves a budget in Accessibility is a business decision, not a compliance scramble.

Output that has no component yet

A site renders templates from many contrib modules, and not all of them will have a component. DRAST handles them in layers:

  • A module can ship components the way it ships Twig templates: templates/mywidget/mywidget.tsx registers mymodule:mywidget, and a theme can still override it.
  • The framework modules (sdx_react, sdx_vue, sdx_svelte) provide base components for core templates, just as core's system module provides base Twig templates.
  • When nothing matches, wrapper templates pass their already-rendered children through, and anything else becomes the active theme's _generic component. It receives the serialized variables plus _templateType and _templateFile. The _generic component in sdx_react_base is a stopgap: a template your site relies on deserves a component of its own.

Some output never becomes a token, because nothing downstream would resolve it. XML responses, such as Views RSS feeds and routes with an XML _format, render the original Twig files through TwigFallbackRenderer for the whole request; the theme registry keeps every hook's original template for exactly this. Mail bodies and content in the document shell, such as page_bottom, render as plain HTML. "Without Twig" describes the theme you write. Twig stays installed, and core uses it where a component tree cannot help.

Trade-offs and when to stay with Twig

  • Contrib themes. Drupal core gives a sub-theme the engine of its root base theme, and the active theme's engine renders every template, base theme templates included. A theme with engine: drast on top of a Twig theme therefore still renders with Twig, and a contrib theme's CSS and JavaScript assume its Twig markup anyway. Start the chain from sdx_react_base.
  • Contrib modules that assume their Twig markup. The generic fallback renders a template's variables, not its Twig file, so the markup can differ. A module whose JavaScript looks for specific classes or wrappers needs a component on your theme. List the contrib templates that matter on your site, give each one a component, and use template debug to see what actually rendered.
  • Team skills. Front-end work moves from Twig to React, Vue or Svelte, with a build step. Back-end skills transfer unchanged and count for more: render arrays, preprocess, cache metadata and access decide what every component receives. A team without front-end framework experience will feel the change.
  • Maturity. sdx_drast is in alpha, and recent releases changed contracts, for example the access rules for DataProvider actions. Pin versions and read the changelog before updating.
  • When Twig is the better fit. A content site that a Twig theme serves well gains little from a full component tree. If you only need a few interactive widgets, SDX components inside a Twig theme are the smaller step.

To try it, require drupal/sdx_drast, enable the module, and create a theme with engine: drast and base theme: sdx_react_base. The project page on drupal.org has releases and the issue queue, and our SDX page shows how the engine fits with the rest of the framework. If you are weighing a component-based theme for a project, we are happy to talk it through.

Written by

Valentin Zsigmond

Founder & Lead Engineer

Full-stack Drupal architect with almost two decades of experience leading large teams in enterprise environments. Founded Tilizy Digital to bring senior-level expertise directly to the organizations that need it. Mentor to dozens of Drupal developers and creator of SDX — a Drupal extension for building modern frontends with React and Vue.

Enjoyed this article?

If this resonated, imagine what we could do working together on your Drupal site.