沃梦达 / 编程问答 / php问题 / 正文

Twig 根据条件扩展模板

Twig extend template on condition(Twig 根据条件扩展模板)

本文介绍了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/

这篇关于Twig 根据条件扩展模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Twig 根据条件扩展模板

基础教程推荐