简体   繁体   中英

Twig, Symfony2: Extend template conditionally from same action

In my base.html.twig file under one div section the render function is called on the Session Controller and editAction , which in turn renders edit.html.twig :

<div class="container">
    {{ render(controller("DefaultBundle:Session:edit", {'id':session.id})) }}
</div>

The edit.html.twig :

{{ form_start(form) }}
    {{ form_errors(form) }}
    <div>
        <p>Fill in the form below to change the data:</p>
        <div class="session_form">
            {{ form_label(form.title) }}
            {{ form_widget(form.title) }}

            <div id="form_options">
                {{ form_rest(form) }}
            </div>
            <button class="btnSave">Save</button>
        </div>
    </div>
 {{ form_end(form) }}

This all works fine, however, in some circumstances the edit.html.twig file will be displayed to edit an entity in a form, based on the route of the editAction, where as above it can be rendered directly without the need of the route for the editAction. This means no template will be inherited and it will be a plain style with a basic form. I could use "{% extends 'DefaultBundle::base.html.twig' %}" however, this means that sometimes the template will essentially be displayed twice on a page, which isn't pretty, or practical. Is there a way of extending the base.html.twig depending on whether the render(controller{}) is used or not?

You can pass a variable from the controller or a global twig variable from a listener to your view indicating wether to extend the template.

Then combine an ternary if-condition with extends .

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

... where minimum can be a template containing only a content block but the file has to exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM