Search code examples
symfonytwigextendpartialradix

How to exclude a twig partial from a base extend in Symfony on some pages only?


Is there a way to specify an "extend" in Twig to exclude one of its included partials ?

To better explain myself, here is my base.html.twig

<body>
        {% include '/main/_navbar.html.twig' %}
        {% block body %}
            {% for flashError in app.flashes('success') %}
                <div class="alert alert-success" role="alert">{{ message }}</div> 
            {% endfor %}
        {% endblock %}
        {% include '/main/_footer.html.twig' %}
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="{{ asset('script/app.js') }}"></script>
    </body>

On my login page, I do not need my _navbar.html.twig partial. Is there a way to not include (exclude) it knowing my view extends from this base template ? Are there any "options" I could pass behind that extends ?

This is the code I use to extend my base template on my login page :

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

Solution

  • Just wrap the include you don't want to include in a seperate block, then override the block with empty content, e.g.

    base.html.twig

    <body>
            {% block nav %}
                {% include '/main/_navbar.html.twig' %}
            {% endblock %}
            {% block body %}
                {% for flashError in app.flashes('success') %}
                    <div class="alert alert-success" role="alert">{{ message }}</div> 
                {% endfor %}
            {% endblock %}
            {% include '/main/_footer.html.twig' %}
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            <script src="{{ asset('script/app.js') }}"></script>
    </body>
    

    login.html.twig

    {% extends "base.html.twig" %}
    {% block nav %}{% endblock %}
    

    demo