Search code examples
symfonytwigsymfony-forms

Reuseable blocks inside of custom form themes in symfony


I want to call a custom block inside an overwritten theme-block:

{% block file_widget %}
    {% if image is not null %}
        {{ block('imagePreview') }}
    {% endif %}

    {{ block('form_widget') }}
{% endblock %}

{% block imagePreview %}
    <img src="{{ image.getFullPath | imagine_filter('medium_square') }}"
         alt="{{ image.filename }}"/>
{% endblock %}

The imagePreview is not shown. But it is working when I don't use a block. And it is also working when I dont use a FormTypeExtension and create an ImageType instead.

So I guess the file_widgetblock still has the scope of the parent form_div_layout.html.twig and there in fact no imagePreview block exists.

So how can I solve this.

I mean now I solved it by removing the block.

But I just want to know if someone has a solution to this. Maybe there is a way for using reuseable blocks inside of custom form themes in symfony?


Solution

  • Finally I found the solution:

    I just did not 'use' the base template explicit. The form theme worked without this - because symfony falls back the the base form theme when it does not find a block inside the new theme file.

    But it seems then you also can not use custom blocks inside this new theme file.

    So this works now:

    {% use 'form_div_layout.html.twig' %}
    
    {% block file_widget %}
        {% if image is not null %}
            {{ block('imagePreview') }}
        {% endif %}
    
        {{ block('form_widget') }}
    {% endblock %}
    
    {% block imagePreview %}
        <img src="{{ image.getFullPath | imagine_filter('medium_square') }}"
             alt="{{ image.filename }}"/>
    {% endblock %}