Twig 根据条件扩展模板

2022-01-22 00:00:00 layout templates php symfony twig

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?

解决方案

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/

相关文章