1
votes

I've created three templates using Twig. The first one has block A defined in it, the second one extends from the first one, but includes a third template which sets the content of block A.

When loading, through the browser, the url which renders b.html.twig, the content in block A (defined by the 3th template) is not positioned block _A is defined.

Example:

<!-- base.html.twig -->
{% block _css '' %}

{% block _header '' %}
{% block _content '' %}
{% block _footer '' %}

{% block _js '' %}


<!-- layout.html.twig -->
<!-- header and footer are placed in the raight zone -->
{% extends ::base.html.twig %}

{% block _header %}
    {% render "MyBundleBundle:Header:header"  %}
{% endblock %}

{% block _footer %}
    {% render "MyBundleBundle:Footer:footer" %}
{% endblock %}


<!-- my_template.html.twig -->
<!-- content is also placed in the right zone but css and js blocks in the included     template are not placed where declared in base.html.twig -->
{% extends MyBundleBundle::layout.html.twig %}
{% block _content %}
     SOME_CONTENT
     {% include MyBundleBundle::my_included_template.html.twig %}
{% endblock %}


<!-- my_included_template.html.twig -->
{% block _css %}
 <link.......................>
{% endblock %}

{% block _js %}
 <script..................>
{% endblock %}

MORE CONTENT BELONGING TO THE INCLUDED TEMPLATE

What i expect here is, _css blocks content to appear on top of the page and _js block content at the bottom, but that's not happening. I hope you can see where i'm going wrong, thanks!

1
I have edited your question a bit, could you please check if it is what you mean? And could you please check your sentences the next time, it was one big sentence which wasn't very understandable...Wouter J
@Touki {% block _css '' %} is actually perfectly valid syntax. It's a shortcut for blocks with little content.lifo
@lifo Can't find this on the doc but I guess I'm just learning every day.Touki
@Touki twig.sensiolabs.org/doc/tags/extends.html#block-shortcuts You can use literal strings or other dynamic variables. It's very handy sometimes.lifo

1 Answers

1
votes

The include tag does not work the way you think/hope it does. It simply includes the file into the current context. Which means you can't reference blocks. You can only reference blocks in a template that has the extends tag at the top of the file.

You're going to have to restructure the way you've designed your template to make this work for you. Instead of including my_included_template.html.twig you should possibly just render that template directly in your controller. That way it'll have full access to any inherited blocks.