symfony / ux

Symfony UX initiative: a JavaScript ecosystem for Symfony
https://ux.symfony.com/
MIT License
824 stars 298 forks source link

[TwigComponents] [Question] Render component using dynamically passed name #1922

Open Pechynho opened 3 months ago

Pechynho commented 3 months ago

Hi,

I'm trying to render a Twig component using a dynamically passed name. Is there a way to achieve this in Twig? Here is an example of what I'm attempting to do:

{% set my_string = 'Modal' %}
{% component (my_string) with {type: 'success'} %}
    {% block content %}{{ ...content }}{% endblock %}
{% endcomponent %}

I want to be able to dynamically set the component name using the my_string variable. Any guidance or suggestions on how to accomplish this would be greatly appreciated!

Thank you!

WebMamba commented 3 months ago

Do you have an error or something when executing this? You can also do this:

{% set my_string = 'Modal' %}

{{ component(my_string, {
   type: 'success',
   content: ...content
})

but here you need to have your content in a props.

smnandre commented 3 months ago

@WebMamba is right, the only way to call component dynamically is with the component function.

Currently there is no possibility to embed content into components with dynamic name.

seb-jean commented 3 months ago

Maybe we could take inspiration from this: https://laravel.com/docs/11.x/blade#dynamic-components

smnandre commented 3 months ago

You can call dynamic component already. It's embedding a component that does not work

seb-jean commented 3 months ago

Sorry! ☺️

tibobaldwin commented 3 months ago

Inspired by what @seb-jean said, we could perhaps create a dynamic-component component like for icons and then use it with HTML Syntax.

Without content:

{% set component_name = 'Modal' %}

<twig:ux:dynamic-component component="{{ component_name }}" />

With content:

{% set component_name = 'Modal' %}

<twig:ux:dynamic-component component="{{ component_name }}">
    {{ block(outerBlocks.content) }}
</twig:ux:dynamic-component>

So the content can be passed with dynamic component names.

smnandre commented 3 months ago

This is not the real problem, for now the component tag does not allow dynamic bloc names.

The HTML syntax is only sugar on top of it