Symfony twig extends: 'only expands if'

The branch has the 'extends' tag, which is located here; http://twig.sensiolabs.org/doc/tags/extends.html#conditional-inheritance

Now what I want to do is something like the lines in the following example from this page:

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

      

But instead of having 2 templates to extend, I just want to move from the template if a specific condition is met.

Now I've tried things like:

{% extends boolean ? "template.html.twig" : "" %}

      

and

{% if boolean %}
    {% extends "template.html.twig" %}
{% endif %}

      

but the former gives an error stating that it cannot find the pattern (since "is obviously not a valid path), and the latter just does nothing at all (more precisely, it loads for a while and ends up showing nothing)

I tried some other approaches but couldn't come up with anything, so thought I would ask if I might be missing something.

Thanks for any answers :)

EDIT: Take stock of my intentions; I am wondering if I can say that my template only expands if a certain condition is met, and skip the expanding step otherwise. (if the condition then proceeds elsewhere, do nothing)

+3


source to share


3 answers


Twig files are generated into PHP classes.

The extends tag should be the first tag in the template, for example:

  • the tag {% extends %}

    will be converted to PHP extends

    so that the child template inherits the parent template.

  • The tag is {% if %}

    generated as PHP if

    inside the template class method, so you cannot use {% if %}

    to extend any class or not.

In any case, you can expand the variable coming from your context, so you have to put your condition in the controller.



if ($boolean) {
  $template = 'hello.twig';
} else {
  $template = 'world.twig';
}
$this->render("MyBundle:MyFeature:child.html.twig", array('template' => $template);

      

And then in child.html.twig

:

{% extends template %}

      

+3


source


I came up with this hack: added an empty layout with just a content block. I seem to be working :) I can pass a variable from the controller and the page is loaded with or without layout.



<!-- base.html.twig -->
<head>
    ...stuff...
</head>
<body>
    {% block content %}{% endblock %}
</body>

<!-- empty.html.twig -->
{% block content %}{% endblock %}

<!-- some_page.html.twig -->
{% extends boolean ? 'base.html.twig' : 'empty.html.twig' %}
{% block content %}
    Now this is my real content
{% endblock %}

      

+1


source


In plain language, it could be something like this:

{% if app.request.pathinfo starts with '/react' %}
    {% set extendPath = "::react_base.html.twig" %}
{% else %}
    {% set extendPath = "CoreBundle::layout.html.twig" %}
{% endif %}
{% extends extendPath %}

      

0


source







All Articles