ux icon indicating copy to clipboard operation
ux copied to clipboard

[TwigComponent] Test helper can't render blocks when limiting scope using `{% with … only%}`

Open janopae opened this issue 4 weeks ago • 1 comments

When defining blocks, I tend to wrap them inside

{% with allowedVariables only %}

{% endwith %}

I do that so I don't have to worry about users of my component depending on variables I only defined internally, which I might want to refactor or remove in the future without checking for usages or declaring a new major version in a library.

The {% with … only %} unfortunately also blocks variables from the outer scope – so when I use a component like

{% set variableIDefinedMyself = 'foo' %}
<twig:My:Component>
    {{ variableIDefinedMyself }}
</twig:My:Component>

this will also be blocked.

I circumvent that by adding outerScope to the variables in {% with … and using it like this:

{% set variableIDefinedMyself = 'foo' %}
<twig:My:Component>
    {{ outerScope.variableIDefinedMyself }}
</twig:My:Component>

However, when trying to test a component like this, the renderTwigComponent function inside InteractsWithTwigComponents fails to render it.

This is because internally, it will try to render a template like this:

{% component "My:Component" with data %}{% block myBlock %}{{ blocks.myBlock|raw }}{% endblock %}{% endcomponent %}

But the blocks variable won't be available in the scope of the block.

Here's a reproducer for the problem: https://github.com/janopae/reproduce-symfony-ux-blocks-cant-be-rendered-in-tests

janopae avatar Dec 04 '25 16:12 janopae

It is not about cannot render blocks, quite the opposite actually.

The thing InteractsWithTwigComponents cannot do here is render component without rendering blocks. Passing mock content via a blocks var is indeed not working, due to {% with %}.

I did not know this behaviour before. I am also not completely sure that using {% with %} like this may not introduce other issues in Twig or Live components.

Did you try to override the trait method in your test classes? Since you already have a workaround that matches how you use the components, it may be better to create a small custom test method or helper for this specific case.

smnandre avatar Dec 07 '25 05:12 smnandre