Twig extend template on condition

Dan Cearnau picture Dan Cearnau · Oct 22, 2011 · Viewed 24k times · Source

I use Symfony 2 with Twig and my question is pretty straightforward:

In a view I want to extend one of the layouts based on a variable. If the variable is false I want to extend UdoWebsiteBundle::layout.html.twig and if it's true I want to extend UdoWebsiteBundle::layout_true.html.twig.

Here is the code I tried:

{% block layout_extender %}

    {% if intro == 'false' %}
        {% extends 'UdoWebsiteBundle::layout.html.twig' %}
    {% else %}
        {% extends 'UdoWebsiteBundle::layout_true.html.twig' %}
    {% endif %}

{% endblock %}

I get this error:

Multiple extends tags are forbidden in "UdoWebsiteBundle:home:home.html.twig" at line 7

Is there any other way to achieve this?

Answer

Maerlyn picture Maerlyn · Oct 22, 2011

Try this one:

{% extends intro == 'false' 
    ? 'UdoWebsiteBundle::layout.html.twig' 
    : 'UdoWebsiteBundle::layout_true.html.twig' %}

Idea taken from here: http://jorisdewit.ca/2011/08/27/extending-different-layouts-for-ajax-requests-in-twig-symfony2/