Skip to main content

That's a
new trick.

Blog of Brendan Tuckerman

Home

Single Directory Component cheat sheet


This article at a glance…

Who is this for?

  • Drupal developers working with single directory components (SDCs).
  • You have worked with SDCs before, or have worked on Drupal themes.

Why should I read this?

Single directory components are a very useful addition for front-end developers working with Drupal. Like other elements in Drupal, the documentation is sometimes hard to pull together into one place.

This post provides a quick reference for those working with SDCs.

This version of the cheat sheet targets Drupal 11.x and Drupal Canvas 1.x.


1. Anatomy and required files

my_theme/ ← or any module
└── components/ ← scanned recursively, nest as you like
└── card/
├── card.component.yml ← **required**
├── card.twig ← **required**
├── card.css ← optional, auto-attached
├── card.js ← optional, auto-attached
├── README.md ← optional, shown as documentation
└── thumbnail.png ← optional, preview image

Rule Detail
Discovery Any file matching [a-z0-9_-]+.component.yml under components/
Machine name The yml filename minus .component.yml, e.g. card
Component ID provider:machine-name, e.g. my_theme:card
Sibling files Must share the machine name: card.twig, card.css, card.js
Library Generated for you: core/components.my_theme--card

2. *.component.yml keys

No key is strictly required, but write name and props as a minimum.

Key Type Notes
$schema uri Enables IDE validation (see example below)
name string Human-readable name. Defaults to the machine name
description string Human-readable description
status enum experimental, stable (default), deprecated, obsolete
group string UI category. Defaults to “Other”
props JSON Schema Must be type: object
slots map Named regions for markup
variants map Named visual variants
tags string[] Free-form tags
noUi boolean Hide from UI builders such as Canvas
libraryOverrides library Extra CSS, JS and dependencies
replaces component ID Swap out another component (see section 8)
thirdPartySettings map For contrib modules

Minimal

$schema: https://git.drupalcode.org/project/drupal/-/raw/11.x/core/assets/schemas/v1/metadata.schema.json
name: Card
props:
type: object
properties:
title:
type: string

Full

$schema: https://git.drupalcode.org/project/drupal/-/raw/11.x/core/assets/schemas/v1/metadata.schema.json
name: Card
description: A content card with an optional image.
status: stable
group: Content
tags: [card, teaser]
props:
type: object
required: [title]
properties:
title:
type: string
title: Title
examples: ["Hello world"]
size:
type: string
title: Size
enum: [sm, lg]
meta:enum:
sm: Small
lg: Large
default: sm
slots:
body:
title: Body
description: Main card content.
variants:
featured:
title: Featured
description: Highlighted card.
libraryOverrides:
dependencies:
- core/once

3. Props

Feature Syntax Notes
Types string, number, integer, boolean, array, object, null JSON Schema draft-04
Nullable type: [string, 'null']
Required required: [title] Any required props must also have examples
Choices enum: [sm, lg]
Choice labels meta:enum: { sm: Small } Optional. Core fills in any missing labels from enum
Translatable x-translation-context: Card
PHP object type: Drupal\Core\Template\Attribute Any class or interface name works
Names ^[a-zA-Z_][a-zA-Z0-9_]*$ No hyphens. Each name becomes a Twig variable
  • Schema enforcement: modules must always define props. Themes may skip them unless the theme’s .info.yml sets enforce_prop_schemas: true.
  • attributes: you get this for free. Core creates an Attribute object with data-component-id already set, so use <div{{ attributes }}>.
  • Unknown props: additionalProperties is always forced to false.

4. Slots

A slot holds markup, such as nested components, render arrays or rich HTML. Use a prop when the value is typed data.

slots:
body:
title: Body
description: Main card content.
{% block body %}{# Fallback content, shown when the slot is empty. #}{% endblock %}
Key Type Notes
title string Required by Canvas
description string
examples string[]
expected string[] Component IDs you expect in this slot
minItems / maxItems integer
  • Slot names follow the same rules as prop names: ^[a-zA-Z_][a-zA-Z0-9_]*$.
  • A slot and a prop can’t share a name.
  • Core doesn’t validate what you put in a slot.

5. Variants

A variant is a prop with a reserved name, variant. The variants: block only lists the allowed values, so UIs such as Canvas can offer them as choices.

card.component.yml
variants:
featured:
title: Featured
banana:
title: Banana
{# Choose one when rendering. In PHP, use '#variant' => 'featured'. #}
{{ include('my_theme:card', { title: 'Hello', variant: 'featured' }, with_context = false) }}
/* Core adds data-component-variant, so style against it. */
.card[data-component-variant="featured"] {
border-left: 4px solid gold;
}
  • Variant names can be anything matching ^[a-zA-Z0-9_-]+$.
  • Inside the template, the chosen value is available as {{ variant }}.
  • Core does not check the value against variants:, so variant: 'kiwi' still renders.

Other reserved names

Name What core does
attributes Always an Attribute object, with data-component-id set
componentMetadata Set by core in Twig. A prop with this name is silently overwritten

6. Putting it together: a component template

components/card/card.component.yml
$schema: https://git.drupalcode.org/project/drupal/-/raw/11.x/core/assets/schemas/v1/metadata.schema.json
name: Card
props:
type: object
properties:
title:
type: string
title: Title
size:
type: string
title: Size
enum: [sm, lg]
slots:
body:
title: Body
variants:
featured:
title: Featured

{# components/card/card.twig #}
<article{{ attributes.addClass('card', 'card--' ~ size|default('sm')) }}>
{% if title %}
<h2 class="card__title">{{ title }}</h2>
{% endif %}
<div class="card__body">
{% block body %}
{# Fallback content, shown when the slot is empty. #}
{% endblock %}
</div>
</article>
In the template Comes from
{{ title }}, size Props become variables of the same name
{% block body %} Each slot is a Twig block named after the slot
attributes Created by core with data-component-id already set
Variant styling Use the selector .card[data-component-variant="featured"]. Core adds that attribute for you

Use |default() for fallback values. Core doesn’t apply a schema’s default for you.

7. Using a component

Twig: props only

{{ include('my_theme:card', {
title: 'Hello',
variant: 'featured',
}, with_context = false) }}

Twig: with slots

{% embed 'my_theme:card' with { title: 'Hello' } only %}
{% block body %}
<p>Slot content</p>
{% endblock %}
{% endembed %}

PHP render array

$build['card'] = [
'#type' => 'component',
'#component' => 'my_theme:card',
'#variant' => 'featured',
'#props' => ['title' => 'Hello'],
'#slots' => ['body' => ['#markup' => '<p>Slot content</p>']],
'#attributes' => ['class' => ['extra']],
];
Key Purpose
#component Component ID
#variant Sets variant, unless #props already sets it
#props Prop values
#slots Render arrays. Scalar values become #plain_text
#attributes Merged into attributes. #props values take priority
#propsAlter / #slotsAlter Trusted callbacks that alter props or slots

8. Overriding

Replace a component

my_theme/components/card/card.component.yml
replaces: "other_module:card"
  • Both components must define props, and the two schemas must be compatible.
  • If the target does not exist, nothing happens and no error is shown.
  • Modules can use replaces too, not only themes.

Extra assets

libraryOverrides:
dependencies: [core/drupal, core/once]
css:
theme:
card-extra.css: {}
js:
card-extra.js: { attributes: { defer: true } }

CSS layers: base, layout, component, state, theme. Paths are relative to the component directory.

9. Canvas readiness

A component that fails any of these checks is not offered in Canvas.

Checklist

  • props schema present, even in a theme
  • Every prop has a title
  • Every slot has a title
  • Every required prop has examples, and examples[0] is valid. It becomes the default
  • Required arrays set minItems: 1
  • maxItems, if set, is 2 or more
  • No empty string '' in an enum
  • status is not obsolete
  • noUi is not true
  • group is not Elements, which is reserved
  • Every prop has a supported shape (see the table below)

attributes props, typed Drupal\Core\Template\Attribute, are skipped by these checks.

Prop shapes and their widgets

Prop schema Canvas widget
type: string Textfield
type: string, maxLength: 50 Textfield with a limit
type: string, enum Select list
type: string, contentMediaType: text/html, x-formatting-context: block Rich text, block
... with x-formatting-context: inline Rich text, inline
type: string, format: uri-reference Link (internal or external)
type: string, format: uri Link (external only)
type: string, format: date or date-time Date picker
type: string, format: email Email
type: string, $ref: json-schema-definitions://canvas.module/color Color picker
type: integer or number (with optional minimum/maximum) Number
type: integer or number, enum Select list
type: boolean Checkbox
type: object, $ref: json-schema-definitions://canvas.module/image Image upload
type: object, $ref: json-schema-definitions://canvas.module/video File upload (mp4)
type: object, $ref: json-schema-definitions://canvas.module/document File upload

No widget: minLength, pattern (with one exception), multipleOf, and the time, duration, uuid, hostname and ipv4 formats.

Other $refs you can use: image-uri, heading, heading-element, date-range, column-width.

Image prop

image:
title: Image
type: object
$ref: json-schema-definitions://canvas.module/image
# Shape: { src (required), alt, width, height }

Entity reference prop

author:
title: Author
type: object
$ref: json-schema-definitions://canvas.module/content-entity-reference
x-allowed-entity-type-id: user

Entity reference props must be optional and must not have examples.

10. Gotchas

  • New component not showing: run drush cr.
  • Props are not validated: validation runs inside assert(), so turn on zend.assertions in development.
  • Prop and slot share a name: this throws an error.
  • Slashes in the component ID: not allowed.
  • Group name differs: with no group, core’s metadata says “All Components” but the UI category shows “Other”.

11. Further reading