简体   繁体   English

Twig,Symfony2:从同一操作中有条件地扩展模板

[英]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 : 在我的base.html.twig文件中的一个div部分下,在会话控制器editAction上调用了render函数,后者又渲染了edit.html.twig

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

The edit.html.twig : 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. 一切正常,但是,在某些情况下,将显示edit.html.twig文件,以基于editAction的路线以表单形式编辑实体,其中如上所述,可以直接呈现它而无需路线用于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. 我可以使用“ {%extended'DefaultBundle :: base.html.twig'%}” ,但这意味着有时模板实际上会在页面上显示两次,这并不美观,也不实用。 Is there a way of extending the base.html.twig depending on whether the render(controller{}) is used or not? 有没有一种方法可以根据是否使用render(controller {})来扩展base.html.twig?

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 . 然后将三元if-条件与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. ...其中minimum可以是仅包含content块的模板,但是文件必须存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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