Twig extend template on condition Twig extend template on condition symfony symfony

Twig extend template on condition


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/


To keep it neat you should use Twig dynamic inheritance support by using a variable, defined in your controller, as the base template:

{% extends parent_template_var %}

If the variable evaluates to a Twig_Template object, Twig will use it as the parent template.

Define parent_template_var in your controller:

if($intro == 'false')    $parent_template_var = 'UdoWebsiteBundle::layout.html.twig';}else{    $parent_template_var = 'UdoWebsiteBundle::layout_true.html.twig';}return $this->render('::/action.html.twig', array('parent_template_var' => $parent_template_var ));

http://twig.sensiolabs.org/doc/tags/extends.html


Answer from the official documentation:

Conditional Inheritance

As the template name for the parent can be any valid Twig expression, it's possible to make the inheritance mechanism conditional:

{% extends standalone ? "minimum.html" : "base.html" %}

In this example, the template will extend the "minimum.html" layout template if the standalone variable evaluates to true, and "base.html" otherwise.