Twig 根据条件扩展模板根据、模板、条件、Twig

2023-09-07 09:39:08 作者:眼角泪丶谁来擦

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.

OneNote 深度评测 使用资源 插件 模版

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/