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 %}
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" %}
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With