{"slug":"twig-component","title":"twig-component","summary":"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.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:48:37.05702Z","repo":{"url":"https://github.com/smnandre/symfony-ux-skills","stars":191,"forks":15,"license":"MIT","updatedAt":"2026-12-02T03:34:06Z"},"bodyHtml":"<hr>\n<h2>name: twig-component\ndescription: '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.'\nlicense: MIT\nmetadata:\nauthor: Simon André\nurl: <a href=\"https://smnandre.dev\">https://smnandre.dev</a></h2>\n<h1>TwigComponent</h1>\n<p>Reusable UI components with PHP classes + Twig templates. Think React/Vue components, but server-rendered with zero JavaScript.</p>\n<p>Two flavors exist: <strong>class components</strong> (PHP class + Twig template) for components that need logic, services, or computed properties, and <strong>anonymous components</strong> (Twig-only, no PHP class) for simple presentational elements.</p>\n<h2>When to Use TwigComponent</h2>\n<p>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.</p>\n<p>Good candidates: buttons, alerts, cards, badges, icons, form widgets, layout sections, navigation items, table rows, modals (structure only).</p>\n<h2>Installation</h2>\n<pre><code>composer require symfony/ux-twig-component\n</code></pre>\n<h2>Class Component</h2>\n<p>A PHP class annotated with <code>#[AsTwigComponent]</code> paired with a Twig template.</p>\n<pre><code>// src/Twig/Components/Alert.php\nnamespace App\\Twig\\Components;\n\nuse Symfony\\UX\\TwigComponent\\Attribute\\AsTwigComponent;\n\n#[AsTwigComponent]\nfinal class Alert\n{\n    public string $type = 'info';\n    public ?string $message = null;\n    public bool $dismissible = false;\n}\n</code></pre>\n<pre><code>{# templates/components/Alert.html.twig #}\n&lt;div {{ attributes.defaults({class: 'alert alert-' ~ type}) }}&gt;\n    {% block content %}{{ message }}{% endblock %}\n    {% if dismissible %}\n        &lt;button type=\"button\" class=\"close\"&gt;&amp;times;&lt;/button&gt;\n    {% endif %}\n&lt;/div&gt;\n</code></pre>\n<pre><code>{# Usage #}\n&lt;twig:Alert type=\"success\" message=\"Saved!\" /&gt;\n&lt;twig:Alert type=\"danger\" message=\"Error occurred\" dismissible /&gt;\n\n{# With block content instead of message prop #}\n&lt;twig:Alert type=\"warning\"&gt;\n    &lt;strong&gt;Warning:&lt;/strong&gt; Check your input\n&lt;/twig:Alert&gt;\n</code></pre>\n<h2>Anonymous Component (Twig Only)</h2>\n<p>A template is enough: props are declared with <code>{% props %}</code> directly in it. Use for simple presentational components.</p>\n<pre><code>{# templates/components/Button.html.twig #}\n{% props variant = 'primary', size = 'md', disabled = false %}\n\n&lt;button {{ attributes.defaults({\n    class: 'btn btn-' ~ variant ~ ' btn-' ~ size,\n    disabled: disabled,\n}) }}&gt;\n    {% block content %}{% endblock %}\n&lt;/button&gt;\n</code></pre>\n<pre><code>&lt;twig:Button variant=\"danger\" size=\"lg\"&gt;Delete&lt;/twig:Button&gt;\n</code></pre>\n<h2>Props</h2>\n<h3>Public Properties (Class Components)</h3>\n<p>Public properties become props. A prop without a default value is required.</p>\n<pre><code>#[AsTwigComponent]\nfinal class Card\n{\n    public string $title;           // Required\n    public ?string $subtitle = null; // Optional\n    public bool $shadow = true;      // Optional with default\n}\n</code></pre>\n<h3>mount() for Derived State</h3>\n<p>Use <code>mount()</code> to compute values from incoming props. The method runs once during component initialization.</p>\n<pre><code>#[AsTwigComponent]\nfinal class UserCard\n{\n    public User $user;\n    public string $displayName;\n\n    public function mount(User $user): void\n    {\n        $this-&gt;user = $user;\n        $this-&gt;displayName = $user-&gt;getFullName();\n    }\n}\n</code></pre>\n<pre><code>&lt;twig:UserCard :user=\"currentUser\" /&gt;\n</code></pre>\n<h3>Dynamic Props (Colon Prefix)</h3>\n<p>Prefix a prop with <code>:</code> to pass a Twig expression instead of a string literal.</p>\n<pre><code>{# Pass a variable #}\n&lt;twig:Alert :type=\"alertType\" :message=\"flashMessage\" /&gt;\n\n{# Pass an expression #}\n&lt;twig:UserList :users=\"users|filter(u =&gt; u.active)\" /&gt;\n\n{# Since Symfony UX 3.7+: shorthand when the variable has the prop's name #}\n&lt;twig:Alert :message /&gt;   {# same as :message=\"message\" #}\n</code></pre>\n<h2>Blocks (Slots)</h2>\n<p>Blocks let parent templates inject content into specific areas of a component.</p>\n<h3>Default Block</h3>\n<p>Content between component tags goes to <code>{% block content %}</code>:</p>\n<pre><code>{# Component template #}\n&lt;div class=\"card\"&gt;{% block content %}{% endblock %}&lt;/div&gt;\n\n{# Usage #}\n&lt;twig:Card&gt;&lt;p&gt;This is the card content&lt;/p&gt;&lt;/twig:Card&gt;\n</code></pre>\n<h3>Named Blocks</h3>\n<pre><code>{# templates/components/Modal.html.twig #}\n&lt;dialog {{ attributes.defaults({class: 'modal'}) }}&gt;\n    &lt;header&gt;{% block header %}Default Header{% endblock %}&lt;/header&gt;\n    &lt;main&gt;{% block content %}{% endblock %}&lt;/main&gt;\n    &lt;footer&gt;{% block footer %}{% endblock %}&lt;/footer&gt;\n&lt;/dialog&gt;\n</code></pre>\n<pre><code>&lt;twig:Modal&gt;\n    &lt;twig:block name=\"header\"&gt;&lt;h2&gt;Confirm Action&lt;/h2&gt;&lt;/twig:block&gt;\n    &lt;twig:block name=\"content\"&gt;&lt;p&gt;Are you sure?&lt;/p&gt;&lt;/twig:block&gt;\n    &lt;twig:block name=\"footer\"&gt;\n        &lt;button&gt;Cancel&lt;/button&gt;\n        &lt;button&gt;Confirm&lt;/button&gt;\n    &lt;/twig:block&gt;\n&lt;/twig:Modal&gt;\n</code></pre>\n<h2>Computed Properties</h2>\n<p>Methods prefixed with <code>get</code> become accessible as <code>this.xxx</code> in templates. They run on each access; read them through <code>computed.xxx</code> instead to cache the result for the rest of the render.</p>\n<pre><code>#[AsTwigComponent]\nfinal class ProductCard\n{\n    public Product $product;\n\n    public function getFormattedPrice(): string\n    {\n        return number_format($this-&gt;product-&gt;getPrice(), 2) . ' EUR';\n    }\n\n    public function isOnSale(): bool\n    {\n        return $this-&gt;product-&gt;getDiscount() &gt; 0;\n    }\n}\n</code></pre>\n<pre><code>&lt;div class=\"product\"&gt;\n    &lt;span class=\"price\"&gt;{{ this.formattedPrice }}&lt;/span&gt;\n    {% if this.onSale %}\n        &lt;span class=\"badge\"&gt;Sale!&lt;/span&gt;\n    {% endif %}\n&lt;/div&gt;\n</code></pre>\n<h2>Attributes</h2>\n<p>Extra HTML attributes passed to the component are available via <code>{{ attributes }}</code>. This is how you let consumers add custom classes, ids, data attributes, etc.</p>\n<p>If consumer attributes are lost or duplicate a default, check the <a href=\"references/gotchas.md#attributes\">attribute merge and rendering examples</a>.</p>\n<pre><code>{# Usage #}\n&lt;twig:Alert type=\"info\" message=\"Hello\" class=\"my-class\" id=\"main-alert\" data-controller=\"alert\" /&gt;\n\n{# In component template -- renders class, id, data-controller #}\n&lt;div {{ attributes }}&gt;...&lt;/div&gt;\n</code></pre>\n<h3>Attributes Methods</h3>\n<pre><code>{# Merge with defaults #}\n&lt;div {{ attributes.defaults({class: 'alert'}) }}&gt;\n\n{# Exclude specific #}\n&lt;div {{ attributes.without('id', 'class') }}&gt;\n\n{# Only render specific #}\n&lt;div id=\"{{ attributes.render('id') }}\"&gt;\n\n{# Check existence #}\n{% if attributes.has('disabled') %}\n</code></pre>\n<h3>Attribute Values</h3>\n<p>Since Symfony UX 3.5+, attributes render through <code>html_attr()</code> from <code>twig/html-extra</code>, exactly like a plain Twig template:</p>\n<table>\n<thead>\n<tr>\n<th>Value</th>\n<th>Renders</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>true</code></td>\n<td><code>name=\"\"</code> (<code>data-*</code> and <code>aria-*</code>: <code>name=\"true\"</code>)</td>\n</tr>\n<tr>\n<td><code>false</code></td>\n<td>omitted (<code>aria-*</code>: <code>name=\"false\"</code>)</td>\n</tr>\n<tr>\n<td><code>null</code></td>\n<td>omitted</td>\n</tr>\n<tr>\n<td>array, iterable, <code>BackedEnum</code></td>\n<td>supported</td>\n</tr>\n</tbody>\n</table>\n<pre><code>&lt;twig:Input type=\"text\" :autofocus=\"true\" :aria-invalid=\"false\" /&gt;\n{# &lt;input type=\"text\" autofocus=\"\" aria-invalid=\"false\"/&gt; #}\n</code></pre>\n<h2>Sharing State With provide / inject</h2>\n<p>Since Symfony UX 3.1+, pass values from a parent to deeply nested descendants without forwarding props through every level:</p>\n<pre><code>{# templates/components/Tabs.html.twig #}\n{% props active = 'general' %}\n{% do provide('tabs.active', active) %}\n\n&lt;div class=\"tabs\"&gt;{% block content %}{% endblock %}&lt;/div&gt;\n</code></pre>\n<pre><code>{# templates/components/Tabs/Panel.html.twig #}\n{% props name %}\n{% set active = inject('tabs.active', null) %}\n\n&lt;section {{ attributes.defaults({hidden: name != active}) }}&gt;\n    {% block content %}{% endblock %}\n&lt;/section&gt;\n</code></pre>\n<p>Values flow top-down only, <code>inject()</code> reads the nearest ancestor (never the current component), and the second argument is the fallback. Call <code>provide()</code> at the top of the parent template, before <code>{% block content %}</code>; it throws outside a component template. Prefix keys with the component name to avoid collisions.</p>\n<h2>Dynamic Component Names</h2>\n<pre><code>{# Since Symfony UX 3.5+, HTML syntax: the is attribute #}\n&lt;twig:component is=\"{{ componentName }}\" type=\"success\" /&gt;\n\n{# Since Symfony UX 3.4+, Twig syntax: wrap the expression in parentheses #}\n{% component (prefix ~ i) %}{% endcomponent %}\n</code></pre>\n<h2>Components as Services</h2>\n<p>Components are Symfony services: autowiring works naturally. Use the constructor for dependencies, public properties for props.</p>\n<pre><code>#[AsTwigComponent]\nfinal class FeaturedProducts\n{\n    public function __construct(\n        private readonly ProductRepository $products,\n    ) {}\n\n    public function getProducts(): array\n    {\n        return $this-&gt;products-&gt;findFeatured(limit: 6);\n    }\n}\n</code></pre>\n<pre><code>{# templates/components/FeaturedProducts.html.twig #}\n&lt;div class=\"featured-products\"&gt;\n    {% for product in this.products %}\n        &lt;twig:ProductCard :product=\"product\" /&gt;\n    {% endfor %}\n&lt;/div&gt;\n</code></pre>\n<pre><code>{# Usage -- no props needed, data comes from service #}\n&lt;twig:FeaturedProducts /&gt;\n</code></pre>\n<h2>Lifecycle Hooks</h2>\n<pre><code>use Symfony\\UX\\TwigComponent\\Attribute\\PreMount;\nuse Symfony\\UX\\TwigComponent\\Attribute\\PostMount;\n\n#[AsTwigComponent]\nfinal class DataTable\n{\n    public array $data;\n    public string $sortBy = 'id';\n\n    #[PreMount]\n    public function preMount(array $data): array\n    {\n        // Modify/validate incoming data before property assignment\n        $data['sortBy'] ??= 'id';\n        return $data;\n    }\n\n    #[PostMount]\n    public function postMount(): void\n    {\n        // Runs after all props are set\n        $this-&gt;data = $this-&gt;sortData($this-&gt;data);\n    }\n}\n</code></pre>\n<h2>Nested Components</h2>\n<p>Components compose naturally: nest them like HTML elements:</p>\n<pre><code>&lt;twig:Card&gt;\n    &lt;twig:block name=\"header\"&gt;\n        &lt;twig:Icon name=\"star\" /&gt; Featured\n    &lt;/twig:block&gt;\n    &lt;twig:block name=\"content\"&gt;\n        &lt;twig:ProductList :products=\"featuredProducts\"&gt;\n            &lt;twig:block name=\"empty\"&gt;\n                &lt;twig:Alert type=\"info\" message=\"No products found\" /&gt;\n            &lt;/twig:block&gt;\n        &lt;/twig:ProductList&gt;\n    &lt;/twig:block&gt;\n&lt;/twig:Card&gt;\n</code></pre>\n<h2>Configuration</h2>\n<pre><code># config/packages/twig_component.yaml\ntwig_component:\n    anonymous_template_directory: 'components/'\n    defaults:\n        App\\Twig\\Components\\: 'components/'\n</code></pre>\n<p><code>defaults</code> is required and must contain at least one namespace/directory pair.</p>\n<h2>Variants With html_cva</h2>\n<p>Use the <code>html_cva()</code> function from <code>twig/html-extra</code> for class variants:</p>\n<pre><code>{# templates/components/Button.html.twig #}\n{% props color = 'blue', size = 'md' %}\n{% set button = html_cva(\n    base: 'btn',\n    variants: {\n        color: {blue: 'btn-blue', red: 'btn-red'},\n        size: {sm: 'btn-sm', md: 'btn-md', lg: 'btn-lg'}\n    },\n    default_variants: {size: 'md'}\n) %}\n\n&lt;button class=\"{{ button.apply({color, size}, attributes.render('class')) }}\" {{ attributes }}&gt;\n    {% block content %}{% endblock %}\n&lt;/button&gt;\n</code></pre>\n<p><code>attributes.render('class')</code> marks <code>class</code> as rendered, so the following <code>{{ attributes }}</code> does not output it a second time.</p>\n<h2>HTML vs Twig Syntax</h2>\n<pre><code>{# HTML syntax (recommended -- better IDE support, more readable) #}\n&lt;twig:Alert type=\"success\" message=\"Done!\" /&gt;\n\n{# Twig syntax (alternative -- useful in edge cases) #}\n{% component 'Alert' with {type: 'success', message: 'Done!'} %}\n{% endcomponent %}\n</code></pre>\n<p>Prefer HTML syntax (<code>&lt;twig:...&gt;</code>) in templates. The Twig syntax (<code>{% component %}</code>) stays fully supported, and reads best inside other Twig tags or with a computed name.</p>\n<h2>References</h2>\n<ul>\n<li><a href=\"https://ux.symfony.com/twig-component\">Symfony UX package page</a> (<a href=\"https://ux.symfony.com/twig-component.md\">Markdown summary</a>) · <a href=\"https://packagist.org/packages/symfony/ux-twig-component\"><code>symfony/ux-twig-component</code> on Packagist</a>.</li>\n<li>Try the <a href=\"https://ux.symfony.com/twig-component#demo\">TwigComponent demo</a>.</li>\n<li>For props, component syntax, lifecycle and configuration, see the <a href=\"https://symfony.com/bundles/ux-twig-component\">Symfony UX TwigComponent documentation</a>.</li>\n<li><strong>Full API</strong> (attribute options, hooks, configuration, all methods): <a href=\"references/api.md\">references/api.md</a></li>\n<li><strong>Patterns</strong> (forms, tables, layouts, composition, real-world examples): <a href=\"references/patterns.md\">references/patterns.md</a></li>\n<li><strong>Gotchas</strong> (attributes, naming, nested components, common pitfalls): <a href=\"references/gotchas.md\">references/gotchas.md</a></li>\n</ul>\n<h2>See Also</h2>\n<ul>\n<li><strong>live-component</strong>: the same component, re-rendered on user input</li>\n<li><strong>ux-toolkit</strong>: ready-made components (Shadcn UI, Flowbite, Bootstrap) installed with <code>ux:install</code></li>\n<li><strong>ux-css</strong>: <code>css()</code> and <code>cva()</code> for token-based classes in component templates</li>\n<li><strong>ux-icons</strong>: <code>&lt;twig:ux:icon name=\"lucide:check\" /&gt;</code> inside component markup</li>\n<li><strong>ux-image</strong>, <strong>ux-map</strong>: render <code>&lt;twig:ux:image&gt;</code> or <code>ux_map()</code> inside a component</li>\n</ul>\n","files":[{"path":"references/api.md","sizeBytes":10559,"isText":true},{"path":"references/gotchas.md","sizeBytes":9940,"isText":true},{"path":"references/patterns.md","sizeBytes":12670,"isText":true},{"path":"SKILL.md","sizeBytes":12563,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:49:15.437119Z","sha256":"3EF60FA8206D77419CEBA6483E6101B9BF65412D458C45C5B2A7295E94E6F021","sizeBytes":15534},"review":null,"source":{"repositoryUrl":"https://github.com/smnandre/symfony-ux-skills","path":"skills/twig-component","license":"MIT","commit":"78c25ed0b79bcc21d7611002dc81d8b87c3316e2","subtreeSha":"C431BB7A4C9D352DF4D34F86262FE749B3E7279CD64B2F92DA3041633958F65A","lastSyncedAt":"2026-12-02T16:48:36.132977Z"},"reviewedAt":"2026-12-02T16:50:34.941049Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/smnandre/symfony-ux-skills/tree/main/skills/twig-component"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install smnandre-symfony-ux-skills@llmmart"},{"target":"git","command":"git clone https://github.com/smnandre/symfony-ux-skills.git"}]}