Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Inheritance in Twig

Tags:

twig

symfony

I have different layouts depending on the user. This triggers the following error: "Multiple extends tags are forbidden". How can I manage to use different layouts depending on the role of the user?

{% if is_granted('ROLE_USER_ONE') %}

{% extends "AcmeUserBundle::layout_user_one.html.twig" %}

{% elseif is_granted('ROLE_USER_TWO') %}

{% extends "AcmeUserBundle::layout_user_two.html.twig" %}

{% endif %}

EDIT

Here is the answer. I will use the case of 3 users in case people wonder how to do this. In this case admin has also userOne and userTwo privileges in case someone wonders about the else statement. I use Conditional Inheritance in this case, but as suggested in one of the answer, Dynamic Inheritance might be more readable.

{% set admin = false %}

{% set userOne = false %}

{% set userTwo = false %}

{% if is_granted('ROLE_ADMIN') %}

    {% set admin = true %}

{% else %}

    {% if is_granted('ROLE_USER_ONE') %}

        {% set userOne = true %}

    {% elseif is_granted('ROLE_USER_TWO') %}

        {% set userTwo = true %}

    {% endif %}

{% endif %}

{% extends admin ? "AcmeUserBundle::layout_admin.html.twig" : userTwo ? "AcmeUserBundle::layout_user_two.html.twig" : "AcmeUserBundle::layout_user_one.html.twig" %}
like image 261
Mick Avatar asked Feb 22 '26 12:02

Mick


1 Answers

Check out the Conditional Inheritance section in the docs.

If you need more than two options, see the Dynamic Inheritance section:

{% set parent = 'defaultLayout.html.twig' %}
{% if is_granted('ROLE_USER') %}
    {% set parent = 'userLayout.html.twig' %}
{% elseif is_granted('ROLE_ADMIN') %}
    {% set parent = 'adminLayout.html.twig' %}
{% endif %}

{% extends parent %}
like image 129
Elnur Abdurrakhimov Avatar answered Feb 26 '26 01:02

Elnur Abdurrakhimov