Skip to content

Sharing Twig components #2003

@javiereguiluz

Description

@javiereguiluz

Hi folks,

I've been using Twig components for some time, but I mostly used them to code some dynamic UI features.

Lately I'm using more and more Twig components to create UI "building blocks" that later I use to create interfaces. I mostly learned this from this nice blog series by @WebMamba: How to integrate Component Architecture into Symfony?

Now, I need to share those UI components with other applications. But, it looks like this is not possible yet.

The use cases:

(1) ACME company uses the same UI in many apps and want to share these Twig components
(2) A third-party bundle (e.g. SonataAdmin or EasyAdmin) defines components to ease the building of custom features with the same UI

For your consideration, this is how I imagine this feature in practice. Let's use the first use case about ACME company:

(1) Create a new AcmeUiBundle
(2) Define your PHP-based and anonymous Twig components as usual:

acme-ui-bundle/
    src/
        Search/
            SearchComponent.php
    templates/
        Alert/
            Success.html.twig
            Warning.html.twig
        UserAvatar.html.twig
        Search.html.twig

(3) Configure the bundle to tell Symfony that it provides Twig components:

namespace Acme\Bundle\AcmeUiBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
// ...

final class AcmeUiBundle extends Bundle
{
    // ...

    public function addTwigComponents(SomeConfigurator $configurator): void
    {
        $configurator
            // these arguments are the same as in:
            // https://symfony.com/bundles/ux-twig-component/current/index.html#configuration
            ->add(fqcn: __DIR__.'/src', templatesDir: 'templates/', namePrefix: 'Acme')
        ;
    }
}

(4) When you install this bundle in a Symfony app with Symfony UX Twig Component installed, you can start using those imported components like this:

<twig:Acme:Search />
<twig:Acme:Alert:Success> ... </twig:Acme:Alert:Success>

Open questions:

  • What to do if you import Twig components with a namePrefix that collides with an existing prefix in your app? Possible solutions: encourage bundles to not use generic name prefixes (e.g. use <twig:Sonata ... instead of just <twig:Admin ...)
  • Twig components usually require their own CSS/JS assets ... how can we include them automatically when using a component? If not automatically, how can we ease the integration of those bundle assets when using the components?
  • ...

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureNew FeatureRFCRFC = Request For Comments (proposals about features that you want to be discussed)TwigComponent

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions