DEV Community

Cover image for Bundling Your Symfony UX Twig Components
Yonel Ceruto
Yonel Ceruto

Posted on

Bundling Your Symfony UX Twig Components

Have you heard about Symfony UX Twig Components? If not, I recommend starting by reading the official documentation to get firsthand understanding. However, in this article, I will give a brief introduction and then quickly jump to today's main topic: How to bundle Twig Components for reuse in your applications.

Image description

Symfony UX components are divided into two main categories: those consisting of a PHP class (controller) plus a Twig template (user interface) plus optional assets (JavaScript, CSS, etc.), which I will call "FullStack Components" in this article; and those made up solely of a user interface (Twig template and assets), referred to as "UI-only Components," also known as "Anonymous Twig Components."

FullStack components, thanks to their controller (the PHP class), can fetch information from a data source and render it on the user interface (the Twig template), making them incredibly dynamic tools. Think of them as compact, reusable controllers, each with a specific responsibility and UI. For example, a table of recommended products could be displayed both on your site's homepage and on individual product pages.

In contrast, the UI-only Components don't have a controller (the PHP class) and are useful when you need to reuse a user interface whose content is static or comes from an unknown data source. For example, a button with a label property or an alert message.

There are also other subcategories of UX components, such as "Live Components," and components whose UI is not rendered using a Twig template but is instead generated at runtime using pure PHP like UX Icon component. I won’t delve deeper into these components here, but you can find more information in the Symfony UX documentation.

Now let's get to the meat of the matter.

Bundling FullStack Components

Following the default recipe configuration, the twig_component extension includes a defaults config. This allows us (the bundles) to prepend new namespaces/paths and register our own FullStack components.

Here is an example of the structure you could follow to achieve this:



acme-bundle/
├── assets/
│   ├── dist/
│   │   ├── controller.js
│   │   └── style.min.css
│   └── package.json
├── src/
│   └── Twig/
│       └── Component/
│           └── Search.php
└── templates/
    └── components/
        └── Search.html.twig


Enter fullscreen mode Exit fullscreen mode

The components/ directory is not mandatory for FullStack components; they can be placed at the root of the templates if your bundle focuses solely on UX components. However, it’s necessary for UI-only components. Therefore, I’ve placed both types under the same directory for consistency.

Here is the configuration you need to add to make the FullStack component work:



class AcmeBundle extends AbstractBundle
{
    public function prependExtension(ContainerConfigurator $container, ContainerBuilder $builder): void
    {
        $builder->prependExtensionConfig('twig_component', [
            'defaults' => [
                'AcmeBundle\Twig\Component\\' => [
                    'template_directory' => '@Acme/components/',
                    'name_prefix' => 'Acme',
                ],
            ],
        ]);
    }

    // ...
}


Enter fullscreen mode Exit fullscreen mode

Although the term defaults in the configuration might be a bit misleading (terms like mappings or namespaces might be clearer), this section allows you to register your own Twig components namespace and the necessary options to locate them.

Here's a trick: the template_directory isn't actually a directory path but rather a prefix for Twig template paths. It's unclear if this is intentional, but that's how it's used in the code. By taking advantage of this, I prefixed the path with the @Acme/ namespace. It worked perfectly!

Ensure the namespace you use matches the one assigned to your bundle by the TwigBundle. You can use the debug:twig command to find this out. If there's a mismatch, Twig won’t be able to locate your component templates.

For consistency, also use this namespace for the name_prefix option. If your Search.php component controller doesn't directly specify a component name, it will default to using this prefix. For instance, the component name would be Acme:Search by default.

If your UX component requires certain assets and your application uses the AssetMapper component, the simplest approach is to prepend the asset path as well:



class AcmeBundle extends AbstractBundle
{
    public function prependExtension(ContainerConfigurator $container, ContainerBuilder $builder): void
    {
        $container->prependExtensionConfig('framework', [
            'asset_mapper' => [
                'paths' => [
                    __DIR__.'/../../assets/dist' => '@symfony/ux-acme-component',
                ],
            ],
        ]);
    }

    // ...
}


Enter fullscreen mode Exit fullscreen mode

This will guarantee that your assets are imported correctly and associated with your component. And that wraps up everything about FullStack Twig Components!

From here, you can reuse your components across any application using either syntax:



<twig:Acme:Search></twig:Acme:Search>  

or  

{{ component('Acme:Search') }}


Enter fullscreen mode Exit fullscreen mode

Bundling UI-only Components

Handling UI-only components is more complex because there is only one anonymous_template_directory. I believe we can improve this by allowing the registration of custom paths, similar to what we do with FullStack components. However, the term used here is misleading—it's not a directory path but a Twig template prefix. This prefix is used to concatenate and locate the template.

UI-only components follow a different convention from FullStack components, so they can't be located in the same way. Let’s look at an example to illustrate this:



<twig:Acme:Alert></twig:Acme:Alert>


Enter fullscreen mode Exit fullscreen mode

Even if you store the Alert component in the <acme-bundle>/templates/components/ directory, you will encounter the following error:

Error rendering "Acme:Alert" component: Unknown component "Acme:Alert". And no matching anonymous component template was found.

The issue arises because the loading mechanism for UI-only components relies on the anonymous_template_directory configuration, which by default points to the templates/components/ directory in your application's path, not in the bundle path as you might expect. So, what can we do about this?

Behind the scenes, the component template finder service attempts to locate the template at templates/components/Acme/Alert.html.twig. Naturally, this template doesn't exist at the application location.

To address this issue, start by creating a new directory named Acme/ within the existing templates/components/ directory in your bundle. Then, place the Alert.html.twig template inside this new directory:



acme-bundle/
└── templates/
    └── components/
        ├── Acme/
        │   └── Alert.html.twig
        └── Search.html.twig


Enter fullscreen mode Exit fullscreen mode

This adjustment partially resolves the issue. However, we still need to ensure that the loader searches within the bundle path. Fortunately, there is a Twig feature that can assist us with this.

In Twig, if a template name lacks a namespace, the loader will search all registered paths that don't specify a namespace. You can identify these paths by running the debug:twig command ((None) namespace).

So, how about registering unnamespaced Twig paths within your bundle's context? This trick lets Twig access the bundle's templates without needing a namespace. However, keep in mind this is more of a workaround to help the loader locate your bundle templates, specifically those under the templates/components/Acme/ directory:



final class AcmeBundle extends AbstractBundle
{
    public function prependExtension(ContainerConfigurator $container, ContainerBuilder $builder): void
    {
        // ...

        $builder->prependExtensionConfig('twig', [
            'paths' => [
                'templates/bundles/AcmeBundle/' => null,
                dirname(__DIR__).'/templates/' => null,
            ],
        ]);
    }
}


Enter fullscreen mode Exit fullscreen mode

Great! Now you can render your <twig:Acme:Alert> component. Just refresh the page, and it will display the component from <acme-bundle>/templates/components/Acme/Alert.html.twig.

Overriding Your Bundled UX Components

Sometimes, your generic UX components require UI tweaks. Consider a scenario where you're using a Bootstrap or Tailwind bundle that packages common UX components. Instead of creating entirely new components, including PHP controllers, you can simply override the Twig template (UI) by following the same TwigBundle convention.

The overriding rule works on a priority basis: the first template found takes precedence. That's why we registered the path 'templates/bundles/AcmeBundle/' => null at a high position in the prepend method.

Simply place your customized templates in templates/bundles/AcmeBundle/, following the same organization as the bundle, and the Twig loader will handle the rest, ensuring your modifications are used:



your-app/
└── templates/
    └── bundles/
        └── AcmeBundle/
            └── components/
                ├── Acme/
                │   └── Alert.html.twig
                └── Search.html.twig


Enter fullscreen mode Exit fullscreen mode

Remember, components are designed to be reusable. Avoid creating a UX component unless you're sure it will be used at least twice. It's always better to refactor later, extract, and create a component when there's a real need for it.

Happy hacking! Cheers!

Top comments (4)

Collapse
 
gbtux profile image
Guillaume

Hi. Love this article, but...not working here. Component is loaded WITHOUT any variable but impossible to access any public variable of my component. It seems Symfony knwos my component as an anonymous component (html without any class).

Have you got a full example in Gitlab / Github ?

Thanks !

Collapse
 
yceruto profile image
Yonel Ceruto

Many improvements have been made since this article was written. Please check the official documentation for the latest updates.

Collapse
 
clussiana profile image
Cyril Lussiana

Hi, did you find how to get components with their PHP class ?

Collapse
 
anshul_dashputre_9bd8a03b profile image
Anshul Dashputre

This article is a total game-changer for Symfony devs! Breaking down those complex Twig components into easy-to-understand steps is HUGE. Building reusable components just got a whole lot easier. Anyone else struggling with Symfony UX? This is your new best friend!