twig-component
Symfony UX TwigComponent: reusable Twig buttons, cards, alerts and design system components. Use for twig: tags, #[AsTwigComponent], props, blocks, attributes.defaults(), anonymous components, computed properties, provide()/inject() and html_cva.
Install
npx skills add https://github.com/smnandre/symfony-ux-skills/tree/main/skills/twig-component
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install smnandre-symfony-ux-skills@llmmart
git clone https://github.com/smnandre/symfony-ux-skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole smnandre/symfony-ux-skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
TwigComponent
Reusable UI components with PHP classes + Twig templates. Think React/Vue components, but server-rendered with zero JavaScript.
Two flavors exist: class components (PHP class + Twig template) for components that need logic, services, or computed properties, and anonymous components (Twig-only, no PHP class) for simple presentational elements.
When to Use TwigComponent
Use TwigComponent when you need reusable markup with props but no server re-rendering after the initial render. If the component needs to react to user input (re-render via AJAX, data binding, actions), use LiveComponent instead.
Good candidates: buttons, alerts, cards, badges, icons, form widgets, layout sections, navigation items, table rows, modals (structure only).
Installation
composer require symfony/ux-twig-component
Class Component
A PHP class annotated with #[AsTwigComponent] paired with a Twig template.
// src/Twig/Components/Alert.php
namespace App\Twig\Components;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
#[AsTwigComponent]
final class Alert
{
public string $type = 'info';
public ?string $message = null;
public bool $dismissible = false;
}
{# templates/components/Alert.html.twig #}
<div {{ attributes.defaults({class: 'alert alert-' ~ type}) }}>
{% block content %}{{ message }}{% endblock %}
{% if dismissible %}
<button type="button" class="close">×</button>
{% endif %}
</div>
{# Usage #}
<twig:Alert type="success" message="Saved!" />
<twig:Alert type="danger" message="Error occurred" dismissible />
{# With block content instead of message prop #}
<twig:Alert type="warning">
<strong>Warning:</strong> Check your input
</twig:Alert>
Anonymous Component (Twig Only)
A template is enough: props are declared with {% props %} directly in it. Use for simple presentational components.
{# templates/components/Button.html.twig #}
{% props variant = 'primary', size = 'md', disabled = false %}
<button {{ attributes.defaults({
class: 'btn btn-' ~ variant ~ ' btn-' ~ size,
disabled: disabled,
}) }}>
{% block content %}{% endblock %}
</button>
<twig:Button variant="danger" size="lg">Delete</twig:Button>
Props
Public Properties (Class Components)
Public properties become props. A prop without a default value is required.
#[AsTwigComponent]
final class Card
{
public string $title; // Required
public ?string $subtitle = null; // Optional
public bool $shadow = true; // Optional with default
}
mount() for Derived State
Use mount() to compute values from incoming props. The method runs once during component initialization.
#[AsTwigComponent]
final class UserCard
{
public User $user;
public string $displayName;
public function mount(User $user): void
{
$this->user = $user;
$this->displayName = $user->getFullName();
}
}
<twig:UserCard :user="currentUser" />
Dynamic Props (Colon Prefix)
Prefix a prop with : to pass a Twig expression instead of a string literal.
{# Pass a variable #}
<twig:Alert :type="alertType" :message="flashMessage" />
{# Pass an expression #}
<twig:UserList :users="users|filter(u => u.active)" />
{# Since Symfony UX 3.7+: shorthand when the variable has the prop's name #}
<twig:Alert :message /> {# same as :message="message" #}
Blocks (Slots)
Blocks let parent templates inject content into specific areas of a component.
Default Block
Content between component tags goes to {% block content %}:
{# Component template #}
<div class="card">{% block content %}{% endblock %}</div>
{# Usage #}
<twig:Card><p>This is the card content</p></twig:Card>
Named Blocks
{# templates/components/Modal.html.twig #}
<dialog {{ attributes.defaults({class: 'modal'}) }}>
<header>{% block header %}Default Header{% endblock %}</header>
<main>{% block content %}{% endblock %}</main>
<footer>{% block footer %}{% endblock %}</footer>
</dialog>
<twig:Modal>
<twig:block name="header"><h2>Confirm Action</h2></twig:block>
<twig:block name="content"><p>Are you sure?</p></twig:block>
<twig:block name="footer">
<button>Cancel</button>
<button>Confirm</button>
</twig:block>
</twig:Modal>
Computed Properties
Methods prefixed with get become accessible as this.xxx in templates. They run on each access; read them through computed.xxx instead to cache the result for the rest of the render.
#[AsTwigComponent]
final class ProductCard
{
public Product $product;
public function getFormattedPrice(): string
{
return number_format($this->product->getPrice(), 2) . ' EUR';
}
public function isOnSale(): bool
{
return $this->product->getDiscount() > 0;
}
}
<div class="product">
<span class="price">{{ this.formattedPrice }}</span>
{% if this.onSale %}
<span class="badge">Sale!</span>
{% endif %}
</div>
Attributes
Extra HTML attributes passed to the component are available via {{ attributes }}. This is how you let consumers add custom classes, ids, data attributes, etc.
If consumer attributes are lost or duplicate a default, check the attribute merge and rendering examples.
{# Usage #}
<twig:Alert type="info" message="Hello" class="my-class" id="main-alert" data-controller="alert" />
{# In component template -- renders class, id, data-controller #}
<div {{ attributes }}>...</div>
Attributes Methods
{# Merge with defaults #}
<div {{ attributes.defaults({class: 'alert'}) }}>
{# Exclude specific #}
<div {{ attributes.without('id', 'class') }}>
{# Only render specific #}
<div id="{{ attributes.render('id') }}">
{# Check existence #}
{% if attributes.has('disabled') %}
Attribute Values
Since Symfony UX 3.5+, attributes render through html_attr() from twig/html-extra, exactly like a plain Twig template:
| Value | Renders |
|---|---|
true |
name="" (data-* and aria-*: name="true") |
false |
omitted (aria-*: name="false") |
null |
omitted |
array, iterable, BackedEnum |
supported |
<twig:Input type="text" :autofocus="true" :aria-invalid="false" />
{# <input type="text" autofocus="" aria-invalid="false"/> #}
Sharing State With provide / inject
Since Symfony UX 3.1+, pass values from a parent to deeply nested descendants without forwarding props through every level:
{# templates/components/Tabs.html.twig #}
{% props active = 'general' %}
{% do provide('tabs.active', active) %}
<div class="tabs">{% block content %}{% endblock %}</div>
{# templates/components/Tabs/Panel.html.twig #}
{% props name %}
{% set active = inject('tabs.active', null) %}
<section {{ attributes.defaults({hidden: name != active}) }}>
{% block content %}{% endblock %}
</section>
Values flow top-down only, inject() reads the nearest ancestor (never the current component), and the second argument is the fallback. Call provide() at the top of the parent template, before {% block content %}; it throws outside a component template. Prefix keys with the component name to avoid collisions.
Dynamic Component Names
{# Since Symfony UX 3.5+, HTML syntax: the is attribute #}
<twig:component is="{{ componentName }}" type="success" />
{# Since Symfony UX 3.4+, Twig syntax: wrap the expression in parentheses #}
{% component (prefix ~ i) %}{% endcomponent %}
Components as Services
Components are Symfony services: autowiring works naturally. Use the constructor for dependencies, public properties for props.
#[AsTwigComponent]
final class FeaturedProducts
{
public function __construct(
private readonly ProductRepository $products,
) {}
public function getProducts(): array
{
return $this->products->findFeatured(limit: 6);
}
}
{# templates/components/FeaturedProducts.html.twig #}
<div class="featured-products">
{% for product in this.products %}
<twig:ProductCard :product="product" />
{% endfor %}
</div>
{# Usage -- no props needed, data comes from service #}
<twig:FeaturedProducts />
Lifecycle Hooks
use Symfony\UX\TwigComponent\Attribute\PreMount;
use Symfony\UX\TwigComponent\Attribute\PostMount;
#[AsTwigComponent]
final class DataTable
{
public array $data;
public string $sortBy = 'id';
#[PreMount]
public function preMount(array $data): array
{
// Modify/validate incoming data before property assignment
$data['sortBy'] ??= 'id';
return $data;
}
#[PostMount]
public function postMount(): void
{
// Runs after all props are set
$this->data = $this->sortData($this->data);
}
}
Nested Components
Components compose naturally: nest them like HTML elements:
<twig:Card>
<twig:block name="header">
<twig:Icon name="star" /> Featured
</twig:block>
<twig:block name="content">
<twig:ProductList :products="featuredProducts">
<twig:block name="empty">
<twig:Alert type="info" message="No products found" />
</twig:block>
</twig:ProductList>
</twig:block>
</twig:Card>
Configuration
# config/packages/twig_component.yaml
twig_component:
anonymous_template_directory: 'components/'
defaults:
App\Twig\Components\: 'components/'
defaults is required and must contain at least one namespace/directory pair.
Variants With html_cva
Use the html_cva() function from twig/html-extra for class variants:
{# templates/components/Button.html.twig #}
{% props color = 'blue', size = 'md' %}
{% set button = html_cva(
base: 'btn',
variants: {
color: {blue: 'btn-blue', red: 'btn-red'},
size: {sm: 'btn-sm', md: 'btn-md', lg: 'btn-lg'}
},
default_variants: {size: 'md'}
) %}
<button class="{{ button.apply({color, size}, attributes.render('class')) }}" {{ attributes }}>
{% block content %}{% endblock %}
</button>
attributes.render('class') marks class as rendered, so the following {{ attributes }} does not output it a second time.
HTML vs Twig Syntax
{# HTML syntax (recommended -- better IDE support, more readable) #}
<twig:Alert type="success" message="Done!" />
{# Twig syntax (alternative -- useful in edge cases) #}
{% component 'Alert' with {type: 'success', message: 'Done!'} %}
{% endcomponent %}
Prefer HTML syntax (<twig:...>) in templates. The Twig syntax ({% component %}) stays fully supported, and reads best inside other Twig tags or with a computed name.
References
- Symfony UX package page (Markdown summary) ·
symfony/ux-twig-componenton Packagist. - Try the TwigComponent demo.
- For props, component syntax, lifecycle and configuration, see the Symfony UX TwigComponent documentation.
- Full API (attribute options, hooks, configuration, all methods): references/api.md
- Patterns (forms, tables, layouts, composition, real-world examples): references/patterns.md
- Gotchas (attributes, naming, nested components, common pitfalls): references/gotchas.md
See Also
- live-component: the same component, re-rendered on user input
- ux-toolkit: ready-made components (Shadcn UI, Flowbite, Bootstrap) installed with
ux:install - ux-css:
css()andcva()for token-based classes in component templates - ux-icons:
<twig:ux:icon name="lucide:check" />inside component markup - ux-image, ux-map: render
<twig:ux:image>orux_map()inside a component
Files (symfony-ux-skills)
-
references
-
api.md 10.3 KB
Loading… -
gotchas.md 9.7 KB
Loading… -
patterns.md 12.4 KB
Loading…
-
-
SKILL.md 12.3 KB
--- name: twig-component description: 'Symfony UX TwigComponent: reusable Twig buttons, cards, alerts and design system components. Use for twig: tags, #[AsTwigComponent], props, blocks, attributes.defaults(), anonymous components, computed properties, provide()/inject() and html_cva.' license: MIT metadata: author: Simon André url: https://smnandre.dev --- # TwigComponent Reusable UI components with PHP classes + Twig templates. Think React/Vue components, but server-rendered with zero JavaScript. Two flavors exist: **class components** (PHP class + Twig template) for components that need logic, services, or computed properties, and **anonymous components** (Twig-only, no PHP class) for simple presentational elements. ## When to Use TwigComponent Use TwigComponent when you need reusable markup with props but no server re-rendering after the initial render. If the component needs to react to user input (re-render via AJAX, data binding, actions), use LiveComponent instead. Good candidates: buttons, alerts, cards, badges, icons, form widgets, layout sections, navigation items, table rows, modals (structure only). ## Installation ```bash composer require symfony/ux-twig-component ``` ## Class Component A PHP class annotated with `#[AsTwigComponent]` paired with a Twig template. ```php // src/Twig/Components/Alert.php namespace App\Twig\Components; use Symfony\UX\TwigComponent\Attribute\AsTwigComponent; #[AsTwigComponent] final class Alert { public string $type = 'info'; public ?string $message = null; public bool $dismissible = false; } ``` ```twig {# templates/components/Alert.html.twig #} <div {{ attributes.defaults({class: 'alert alert-' ~ type}) }}> {% block content %}{{ message }}{% endblock %} {% if dismissible %} <button type="button" class="close">×</button> {% endif %} </div> ``` ```twig {# Usage #} <twig:Alert type="success" message="Saved!" /> <twig:Alert type="danger" message="Error occurred" dismissible /> {# With block content instead of message prop #} <twig:Alert type="warning"> <strong>Warning:</strong> Check your input </twig:Alert> ``` ## Anonymous Component (Twig Only) A template is enough: props are declared with `{% props %}` directly in it. Use for simple presentational components. ```twig {# templates/components/Button.html.twig #} {% props variant = 'primary', size = 'md', disabled = false %} <button {{ attributes.defaults({ class: 'btn btn-' ~ variant ~ ' btn-' ~ size, disabled: disabled, }) }}> {% block content %}{% endblock %} </button> ``` ```twig <twig:Button variant="danger" size="lg">Delete</twig:Button> ``` ## Props ### Public Properties (Class Components) Public properties become props. A prop without a default value is required. ```php #[AsTwigComponent] final class Card { public string $title; // Required public ?string $subtitle = null; // Optional public bool $shadow = true; // Optional with default } ``` ### mount() for Derived State Use `mount()` to compute values from incoming props. The method runs once during component initialization. ```php #[AsTwigComponent] final class UserCard { public User $user; public string $displayName; public function mount(User $user): void { $this->user = $user; $this->displayName = $user->getFullName(); } } ``` ```twig <twig:UserCard :user="currentUser" /> ``` ### Dynamic Props (Colon Prefix) Prefix a prop with `:` to pass a Twig expression instead of a string literal. ```twig {# Pass a variable #} <twig:Alert :type="alertType" :message="flashMessage" /> {# Pass an expression #} <twig:UserList :users="users|filter(u => u.active)" /> {# Since Symfony UX 3.7+: shorthand when the variable has the prop's name #} <twig:Alert :message /> {# same as :message="message" #} ``` ## Blocks (Slots) Blocks let parent templates inject content into specific areas of a component. ### Default Block Content between component tags goes to `{% block content %}`: ```twig {# Component template #} <div class="card">{% block content %}{% endblock %}</div> {# Usage #} <twig:Card><p>This is the card content</p></twig:Card> ``` ### Named Blocks ```twig {# templates/components/Modal.html.twig #} <dialog {{ attributes.defaults({class: 'modal'}) }}> <header>{% block header %}Default Header{% endblock %}</header> <main>{% block content %}{% endblock %}</main> <footer>{% block footer %}{% endblock %}</footer> </dialog> ``` ```twig <twig:Modal> <twig:block name="header"><h2>Confirm Action</h2></twig:block> <twig:block name="content"><p>Are you sure?</p></twig:block> <twig:block name="footer"> <button>Cancel</button> <button>Confirm</button> </twig:block> </twig:Modal> ``` ## Computed Properties Methods prefixed with `get` become accessible as `this.xxx` in templates. They run on each access; read them through `computed.xxx` instead to cache the result for the rest of the render. ```php #[AsTwigComponent] final class ProductCard { public Product $product; public function getFormattedPrice(): string { return number_format($this->product->getPrice(), 2) . ' EUR'; } public function isOnSale(): bool { return $this->product->getDiscount() > 0; } } ``` ```twig <div class="product"> <span class="price">{{ this.formattedPrice }}</span> {% if this.onSale %} <span class="badge">Sale!</span> {% endif %} </div> ``` ## Attributes Extra HTML attributes passed to the component are available via `{{ attributes }}`. This is how you let consumers add custom classes, ids, data attributes, etc. If consumer attributes are lost or duplicate a default, check the [attribute merge and rendering examples](references/gotchas.md#attributes). ```twig {# Usage #} <twig:Alert type="info" message="Hello" class="my-class" id="main-alert" data-controller="alert" /> {# In component template -- renders class, id, data-controller #} <div {{ attributes }}>...</div> ``` ### Attributes Methods ```twig {# Merge with defaults #} <div {{ attributes.defaults({class: 'alert'}) }}> {# Exclude specific #} <div {{ attributes.without('id', 'class') }}> {# Only render specific #} <div id="{{ attributes.render('id') }}"> {# Check existence #} {% if attributes.has('disabled') %} ``` ### Attribute Values Since Symfony UX 3.5+, attributes render through `html_attr()` from `twig/html-extra`, exactly like a plain Twig template: | Value | Renders | |-------|---------| | `true` | `name=""` (`data-*` and `aria-*`: `name="true"`) | | `false` | omitted (`aria-*`: `name="false"`) | | `null` | omitted | | array, iterable, `BackedEnum` | supported | ```twig <twig:Input type="text" :autofocus="true" :aria-invalid="false" /> {# <input type="text" autofocus="" aria-invalid="false"/> #} ``` ## Sharing State With provide / inject Since Symfony UX 3.1+, pass values from a parent to deeply nested descendants without forwarding props through every level: ```twig {# templates/components/Tabs.html.twig #} {% props active = 'general' %} {% do provide('tabs.active', active) %} <div class="tabs">{% block content %}{% endblock %}</div> ``` ```twig {# templates/components/Tabs/Panel.html.twig #} {% props name %} {% set active = inject('tabs.active', null) %} <section {{ attributes.defaults({hidden: name != active}) }}> {% block content %}{% endblock %} </section> ``` Values flow top-down only, `inject()` reads the nearest ancestor (never the current component), and the second argument is the fallback. Call `provide()` at the top of the parent template, before `{% block content %}`; it throws outside a component template. Prefix keys with the component name to avoid collisions. ## Dynamic Component Names ```twig {# Since Symfony UX 3.5+, HTML syntax: the is attribute #} <twig:component is="{{ componentName }}" type="success" /> {# Since Symfony UX 3.4+, Twig syntax: wrap the expression in parentheses #} {% component (prefix ~ i) %}{% endcomponent %} ``` ## Components as Services Components are Symfony services: autowiring works naturally. Use the constructor for dependencies, public properties for props. ```php #[AsTwigComponent] final class FeaturedProducts { public function __construct( private readonly ProductRepository $products, ) {} public function getProducts(): array { return $this->products->findFeatured(limit: 6); } } ``` ```twig {# templates/components/FeaturedProducts.html.twig #} <div class="featured-products"> {% for product in this.products %} <twig:ProductCard :product="product" /> {% endfor %} </div> ``` ```twig {# Usage -- no props needed, data comes from service #} <twig:FeaturedProducts /> ``` ## Lifecycle Hooks ```php use Symfony\UX\TwigComponent\Attribute\PreMount; use Symfony\UX\TwigComponent\Attribute\PostMount; #[AsTwigComponent] final class DataTable { public array $data; public string $sortBy = 'id'; #[PreMount] public function preMount(array $data): array { // Modify/validate incoming data before property assignment $data['sortBy'] ??= 'id'; return $data; } #[PostMount] public function postMount(): void { // Runs after all props are set $this->data = $this->sortData($this->data); } } ``` ## Nested Components Components compose naturally: nest them like HTML elements: ```twig <twig:Card> <twig:block name="header"> <twig:Icon name="star" /> Featured </twig:block> <twig:block name="content"> <twig:ProductList :products="featuredProducts"> <twig:block name="empty"> <twig:Alert type="info" message="No products found" /> </twig:block> </twig:ProductList> </twig:block> </twig:Card> ``` ## Configuration ```yaml # config/packages/twig_component.yaml twig_component: anonymous_template_directory: 'components/' defaults: App\Twig\Components\: 'components/' ``` `defaults` is required and must contain at least one namespace/directory pair. ## Variants With html_cva Use the `html_cva()` function from `twig/html-extra` for class variants: ```twig {# templates/components/Button.html.twig #} {% props color = 'blue', size = 'md' %} {% set button = html_cva( base: 'btn', variants: { color: {blue: 'btn-blue', red: 'btn-red'}, size: {sm: 'btn-sm', md: 'btn-md', lg: 'btn-lg'} }, default_variants: {size: 'md'} ) %} <button class="{{ button.apply({color, size}, attributes.render('class')) }}" {{ attributes }}> {% block content %}{% endblock %} </button> ``` `attributes.render('class')` marks `class` as rendered, so the following `{{ attributes }}` does not output it a second time. ## HTML vs Twig Syntax ```twig {# HTML syntax (recommended -- better IDE support, more readable) #} <twig:Alert type="success" message="Done!" /> {# Twig syntax (alternative -- useful in edge cases) #} {% component 'Alert' with {type: 'success', message: 'Done!'} %} {% endcomponent %} ``` Prefer HTML syntax (`<twig:...>`) in templates. The Twig syntax (`{% component %}`) stays fully supported, and reads best inside other Twig tags or with a computed name. ## References - [Symfony UX package page](https://ux.symfony.com/twig-component) ([Markdown summary](https://ux.symfony.com/twig-component.md)) · [`symfony/ux-twig-component` on Packagist](https://packagist.org/packages/symfony/ux-twig-component). - Try the [TwigComponent demo](https://ux.symfony.com/twig-component#demo). - For props, component syntax, lifecycle and configuration, see the [Symfony UX TwigComponent documentation](https://symfony.com/bundles/ux-twig-component). - **Full API** (attribute options, hooks, configuration, all methods): [references/api.md](references/api.md) - **Patterns** (forms, tables, layouts, composition, real-world examples): [references/patterns.md](references/patterns.md) - **Gotchas** (attributes, naming, nested components, common pitfalls): [references/gotchas.md](references/gotchas.md) ## See Also - **live-component**: the same component, re-rendered on user input - **ux-toolkit**: ready-made components (Shadcn UI, Flowbite, Bootstrap) installed with `ux:install` - **ux-css**: `css()` and `cva()` for token-based classes in component templates - **ux-icons**: `<twig:ux:icon name="lucide:check" />` inside component markup - **ux-image**, **ux-map**: render `<twig:ux:image>` or `ux_map()` inside a component
Reviews (0)
No reviews yet.
Comments
Sign in to join the conversation.
No comments yet. Start the conversation.