Search code examples
symfonyincludeblocktwigextends

Redefining a block initially defined in an included view in the parent view with twig


I have a view A that includes a view B that defines a block Z. Can I have a view C that extends A and redefines block Z?

Need not be said that if i paste B into A (without using an include) it works.

For a practical example:

A is the base of a project. B is the header of a project that includes a menu. C is any page of the project.

I define a {% block active %}{% endblock %} for each item of the menu in B, that i want to redefine by {% block active %} class="active" {% endblock %} in C to apply certain styles to the current active menu item.

If this is not the way to go, which is the best workaround/solution?


Solution

  • Unfortunately, it's not possible or it wouldn't be as easy.

    Why not bind a variable to the template from the controller and passing it to the nav through the include?

    {% include MyAwesomeBundle:Modules:nav.html.twig with {activeItem: activeItem, activeItemClassName: activeItemClassName} %}
    

    An alternative to what you want

    {# in base layout template #}
    {% block nav %}
        {% include MyAwesomeBundle:Modules:nav.html.twig %}
    {% endblock %}
    
    {# in page template #}
    {% extends base-layout.html.twig %}
    
    {% block nav %}
        {% include MyAwesomeBundle:Modules:nav_for_news.html.twig %} {# nav_for_news.html.twig extends nav.html.twig #}
    {% endblock %}
    

    This is the closest you can get from what you want

    Check out the parent() twig function it's useful.