4
votes

I am trying to override a {% block %} in a file (index.html.twig) that extends the file where the block is used (base.html.twig). But the extending file is including another twig file (feature.twig) where the block that overrides the content in index.html.twig is placed. Is that possible in any way? Maybe with something else than the include statement?

{# index.html.twig #}
{% extends 'base.html.twig' %}
{{ include('feature.html.twig') }}

{# base.html.twig #}
{% block extraJs %}{% endblock %}

{# feature.html.twig #}
{% block extraJs %}<script>$('...');</script>{% endblock %}
3
include returns the rendered version, so I don't think you can do anything with this setup.Yoshi
Includes cant change the block of the template who included themDarkBee
Please read the updated questioncnmicha
There is something like embed twig.sensiolabs.org/doc/tags/embed.html but I don't think it resolve your problem, sorry.ofca
As index extends base, why not do it the easy way and (in index) declare: {% block extraJs %}{{ include('feature.html.twig') }}{% endblock %}. And in feature just render the content, no blocks.Yoshi

3 Answers

7
votes

The include-function (or tag) only ever embeds the rendered result. It is not possible to manipulate blocks in the including file.

But in your case this is not necessary. Because index.html.twig extends base.html.twig, you can overwrite the block extraJs like so:

{# index.html.twig #}
{% extends 'base.html.twig' %}

{% block extraJs %}
    {{ include('feature.html.twig') }}
{% endblock }

If needed you can extend the original block by using the parent-function. E.g.:

{# index.html.twig #}
{% extends 'base.html.twig' %}

{% block extraJs %}
    {{ parent() }} {# `extraJs`-block content from `base.html.twig` #}
    {{ include('feature.html.twig') }}
{% endblock }
0
votes

No it's not possible. include just render template and include the output. You can't override block using it. Here is a issue related to this problem https://github.com/twigphp/Twig/issues/1360

0
votes

Just as an info,I think you cannot put comments {# index.html.twig #} before the {% extends 'base.html.twig' %} and comments as I understood must be put always in blocks,hope this helps