Drupal · 9 min read · Updated

Single Directory Components in Drupal 11: Build a Product Card With Twig, CSS, JS and Props (Tested Tutorial)

A tested Drupal 11 tutorial: build a product card as a single directory component, use it with include, embed and the component render element, and see when prop validation runs.

Drupal 11 single directory components

In a classic Drupal theme, one card on the page is spread over four places: a Twig template in templates/, CSS in css/, JavaScript in js/, and a library in THEME.libraries.yml that ties them together and has to be attached somewhere. Rename the card or delete it, and you hunt through all four. Drupal 11 single directory components keep all of it in one folder.

Single Directory Components (SDC) put everything for one component in one folder: the Twig template, the CSS, the JavaScript and a YAML file that describes its props and slots. Drupal finds the folder, builds the library and attaches it only on pages that render the component. This tutorial builds a product card component in Drupal 11 single directory components style, uses it from Twig and from PHP, and shows what happens when you pass it bad data. Everything here was tested on Drupal 11.4.14 with PHP 8.5 in a throwaway Docker container.

Download the tested theme: webo-sdc-theme.zip (an Olivero sub-theme with the component and the demo template).

Drupal 11 page titled Shop our favourites with three product cards from a single directory component: a navy T-shirt with a NEW badge, a red T-shirt with a SALE badge and a slot text, and a white T-shirt
Three cards from one component. The middle one has keyboard focus and uses the body slot.

Drupal 11 single directory components: which versions have them

SDC started as an experimental core module. The drupal.org change record says it became stable and was merged into core in Drupal 10.3.0, so “module and theme developers can make use of components without enabling any module or theme.” On Drupal 10.3 and later, including every Drupal 11 release, there is nothing to switch on. The old experimental sdc module is marked obsolete in 11.x and will be removed in 12.x, so drop any dependency on it. If you are still on Drupal 10, note that Drupal 10 reaches end of life on December 9, 2026.

Step 1: Create a theme

Components live in a components/ folder inside a theme or module. For this tutorial we made a small sub-theme of Olivero called Webo in web/themes/custom/webo/:

name: Webo
type: theme
description: 'Olivero sub-theme with single directory components.'
core_version_requirement: ^10.3 || ^11
base theme: olivero

The finished theme has this layout:

webo/
├── webo.info.yml
├── logo.svg
├── images/
├── templates/
│   └── node--page--full.html.twig
└── components/
    └── product-card/
        ├── product-card.component.yml
        ├── product-card.twig
        ├── product-card.css
        └── product-card.js

Copy Olivero’s logo.svg into the sub-theme. Without it, the header shows a broken logo image, because a sub-theme doesn’t inherit the base theme’s logo file.

Step 2: Describe the component

The folder name and the file names must match: product-card/product-card.component.yml. The YAML file has the name, a description, and a JSON Schema for the props. Props are typed data such as strings, numbers and booleans. Slots are free content such as markup or render arrays, and they have no schema.

$schema: https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json
name: Product card
status: stable
description: A product teaser with image, title, price, an optional badge and a slot for extra text.
props:
  type: object
  required:
    - title
    - url
  properties:
    title:
      type: string
      title: Title
    url:
      type: string
      title: Link
    image:
      type: string
      title: Image URL
    price:
      type: string
      title: Price
      examples: ['$24.00']
    badge:
      type: string
      title: Badge
      enum: ['', new, sale]
libraryOverrides:
  dependencies:
    - core/drupal
    - core/once
slots:
  body:
    title: Body
    description: Short text under the price.

Three parts are worth a closer look:

  • required lists the props that must be passed: here the title and the link.
  • enum limits the badge to an empty string, “new” or “sale”. The empty string is in the list so that “no badge” is valid.
  • libraryOverrides adds dependencies to the library Drupal builds for the component. The card’s JavaScript uses Drupal.behaviors and once(), so it needs core/drupal and core/once. Without them, the script can run before those are loaded.

Step 3: The template, CSS and JavaScript

The template is normal Twig. Props arrive as variables with the same names, and every component also gets an attributes object. A slot is a Twig block with the slot’s name:

{%
  set classes = [
    'product-card',
    badge ? 'product-card--' ~ badge,
  ]
%}
<article{{ attributes.addClass(classes) }}>
  {% if image %}
    <img class="product-card__image" src="{{ image }}" alt="" loading="lazy">
  {% endif %}
  {% if badge %}
    <span class="product-card__badge">{{ badge }}</span>
  {% endif %}
  <h3 class="product-card__title"><a href="{{ url }}">{{ title }}</a></h3>
  {% if price %}
    <p class="product-card__price">{{ price }}</p>
  {% endif %}
  <div class="product-card__body">
    {% block body %}{% endblock %}
  </div>
</article>

The CSS sits next to it. The last rule styles the grid around the cards, which a real theme would keep in its own layout CSS:

.product-card { position: relative; display: flex; flex-direction: column; gap: .5rem; padding: 1rem; border: 1px solid #dfe3e8; border-radius: 12px; background: #fff; transition: box-shadow .2s; }
.product-card:hover, .product-card.is-focused { box-shadow: 0 6px 20px rgb(0 0 0 / .08); }
.product-card__image { width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: 8px; background: #f3f4f6; }
.product-card__badge { position: absolute; top: 1.5rem; left: 1.5rem; padding: .15rem .6rem; border-radius: 999px; font-size: .75rem; font-weight: 700; text-transform: uppercase; color: #fff; background: #1e5bd8; }
.product-card--sale .product-card__badge { background: #d32f2f; }
.product-card__title { margin: 0; font-size: 1.15rem; line-height: 1.3; }
.product-card__title a { color: inherit; text-decoration: none; }
.product-card__title a::after { content: ""; position: absolute; inset: 0; }
.product-card__price { margin: 0; font-weight: 700; color: #f6821f; }
.product-card__body { font-size: .9rem; color: #555; }
.product-card-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 1.25rem; }

The JavaScript is a behavior that highlights the whole card while its link has keyboard focus. The title link stretches over the whole card with ::after, so the card is one click target:

((Drupal, once) => {
  Drupal.behaviors.weboProductCard = {
    attach(context) {
      once('product-card', '.product-card', context).forEach((card) => {
        const link = card.querySelector('.product-card__title a');
        link.addEventListener('focus', () => card.classList.add('is-focused'));
        link.addEventListener('blur', () => card.classList.remove('is-focused'));
      });
    },
  };
})(Drupal, once);

You don’t write a libraries.yml entry. Drupal builds one called core/components.webo--product-card from the CSS and JS files it finds in the folder.

Step 4: Use the component in Twig

A component’s ID is theme:folder, here webo:product-card. We used it in a template for Basic pages, templates/node--page--full.html.twig, to render three cards:

{#
  Demo: render three product cards from a Basic page.
  include() passes props only; embed lets you fill the "body" slot.
#}
<article{{ attributes }}>
  <h1>{{ label }}</h1>
  <div class="product-card-grid">
    {{ include('webo:product-card', {
      title: 'Webo Classic Tee, navy',
      url: '/node/1',
      image: '/themes/custom/webo/images/tee-navy.png',
      price: '$24.00',
      badge: 'new',
    }, with_context = false) }}

    {% embed 'webo:product-card' with {
      title: 'Webo Classic Tee, red',
      url: '/node/1',
      image: '/themes/custom/webo/images/tee-red.png',
      price: '$19.20',
      badge: 'sale',
    } only %}
      {% block body %}
        <p>20% off while sizes last.</p>
      {% endblock %}
    {% endembed %}

    {{ include('webo:product-card', {
      title: 'Webo Classic Tee, white',
      url: '/node/1',
      image: '/themes/custom/webo/images/tee-white.png',
      price: '$24.00',
    }, with_context = false) }}
  </div>
</article>
  • include() with with_context = false passes only the props you list. drupal.org’s examples use this form for components without slots. Nothing from the parent template leaks into the component.
  • embed lets you fill slots with {% block %}. The only keyword does the same job as with_context = false.

Install the theme in Appearance with Install and set as default, then clear caches in Configuration > Development > Performance. Drupal only discovers new components after a cache clear.

Check that it worked

Each card in the page source starts with <article data-component-id="webo:product-card" class="product-card product-card--new">. The data-component-id attribute is added by Drupal and tells you which component rendered the markup. With CSS and JS aggregation on, the card’s styles and the weboProductCard behavior were inside the aggregated files on this page. On the login page, which has no cards, neither was loaded.

Step 5: Use the component from PHP

Controllers, block plugins and preprocess functions can render a component with the component render element. drupal.org calls this the preferred way when you want a theme to stay shareable. We rendered this array in the lab:

$build = [
  '#type' => 'component',
  '#component' => 'webo:product-card',
  '#props' => [
    'title' => 'Webo Classic Tee',
    'url' => '/node/2',
    'price' => '$24.00',
    'badge' => 'sale',
  ],
  '#slots' => [
    'body' => ['#markup' => '<p>Back in stock in navy.</p>'],
  ],
];

The output was the same markup as the Twig version, with the slot inside product-card__body. The library was attached automatically:

<article data-component-id="webo:product-card" class="product-card product-card--sale"> <span class="product-card__badge">sale</span> <h3 class="product-card__title"><a href="/node/2">Webo Classic Tee</a></h3> <p class="product-card__price">$24.00</p> <div class="product-card__body"> <p>Back in stock in navy.</p> </div> </article>
["core\/components.webo--product-card"]

Step 6: What prop validation catches, and when

The schema is not only documentation. With PHP assertions on, Drupal checks every prop against it when the component renders, and stops with an error that names the template, the component and the prop. We broke the demo template three ways:

Three Drupal InvalidComponentException messages: price integer value found but a string or an object is required, badge does not have a value in the enumeration, and the property url is required
The three validation errors from the Drupal log.
  • price: 9 (a number instead of a string) gave “Integer value found, but a string or an object is required.” As the message says, Drupal accepts an object where the schema asks for a string, but not a number.
  • badge: 'hot' gave “Does not have a value in the enumeration [“”,”new”,”sale”].”
  • Leaving out url gave “The property url is required.”

The catch is that validation runs through PHP’s assert(), so it only happens when zend.assertions is 1. Drupal’s own example.settings.local.php recommends 1 on development machines and 0 or -1 in production. On a production site, the same mistakes render quietly: the card with badge: 'hot' simply got a product-card--hot class and price: 9 printed “9”.

We found one more trap. Turning assertions on in php.ini wasn’t enough on Apache, because Drupal’s .htaccess contains this line, and it wins under mod_php:

php_value zend.assertions 0

Only after changing it to 1 on the development copy did the errors appear. If you run Apache with mod_php locally and never see component errors, check .htaccess first.

Misspelled slots fail silently in themes

We renamed the slot block in the demo template from body to footer, which the component doesn’t declare. The page rendered with status 200, and the slot text was simply missing. Drupal’s slot check only runs when schemas are mandatory, which applies to components in modules. Components in themes can skip their schema, so their slot names aren’t checked. Keep slot names short and test each component page after a rename.

Override a component from another theme or module

A theme can replace a component from a base theme or a module by adding replaces: 'provider:component' to its own component’s YAML. drupal.org notes that only themes can do this, not modules. We didn’t use it in this lab.

What we found when testing

  • Drupal 11.4.14 found the component and built the core/components.webo--product-card library with no libraries.yml entry.
  • CSS and JS were loaded only on the page that used the component.
  • The libraryOverrides dependencies were needed for Drupal.behaviors and once().
  • Prop validation needed zend.assertions=1 both in PHP and in Drupal’s .htaccess.
  • An undeclared slot in a theme component is dropped without an error.
  • The PHP render element and Twig produced the same markup.

Where to go next

Filed underDrupal
Rupak Nepali
Written byRupak Nepali

Rupak Nepali is a web developer, manage Webocreation website and the author of six books:
Getting Started with OpenCart Module Development (Packt, 2013),
OpenCart Theme and Module Development (Packt, 2015),
OpenCart 4: Dev Guide for Themes & Extensions (2024),
OpenCart 4: User Manual (2025),
Cloudflare for the Enterprise Website (2026) and
The Technical Web Guide for Marketers (2026).
Rupak has built OpenCart stores and extensions since 2010, has published more than 600 tutorials on Webocreation, and shares free OpenCart extensions on GitHub.
Find Rupak on
GitHub | Amazon | LinkedIn | X | YouTube.

Leave a Reply

Your email address will not be published. Required fields are marked *