Tuesday, May 17, 2022

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

Issue

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



Answered By - DarkBee
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.