Skip to content

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

@janopae

Description

@janopae

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions