[英]Symfony2/Twig: Error on conditionally render
I'm trying to render a form on a twig template if its is defined in the render call on controller. 我正在尝试在树枝模板上呈现表单,如果该表单在控制器上的render调用中定义的话。 Something like: 就像是:
{% if form_to_be_rendered is defined %}
{{ form(form_to_be_rendered) }}
{% endif }
If the controller's render call includes the var of form_to_be_rendered
, everything runs well, and the form is rendered. 如果控制器的render调用包含form_to_be_rendered
的var,则一切运行良好,并且呈现了表单。 But if I try to render the template without this argument, Twig throws a RuntimeError
indicating that the form_to_be_rendered
variable is not defined. 但是,如果我尝试不使用此参数来呈现模板,则Twig会抛出RuntimeError
指示form_to_be_rendered
变量。
Variable "form_to_be_rendered" does not exist in BundleName:Path/to/template:template.html.twig at line 3
500 Internal Server Error - Twig_Error_Runtime
I've tried passing it as a null value and is not null
check on condition, but it fails too. 我尝试过将其作为空值传递,并且在条件上is not null
检查,但它也失败。
I put this dump on template: 我把这个转储放在模板上:
{% dump reset_password_form is defined %}
And it is evaluated as false
when I don't pass any arguments to render function. 当我不将任何参数传递给render函数时,它将被评估为false
。
EDIT 编辑
I forgot to post that there is a {% block content %}
inside the conditional block which causes the issue. 我忘记发布条件块内有一个{% block content %}
的问题。 Please view the solution below. 请查看下面的解决方案。
Thanks, 谢谢,
Solved. 解决了。
It's pretty weird and my fault since I don't post the full code on the OP. 这很奇怪,也是我的错,因为我没有在OP上发布完整的代码。
{% if form is defined %}
{% block content%}
{{ form(form)}}
{% end block %}
{% endif %}
The conditional block has inside a {% block content %}
that Twig tries to render even the condition is evaluated to false. 条件块内部有{% block content %}
,即使条件被评估为false,Twig也会尝试渲染该{% block content %}
。 If I surround the conditional block with the content block, the issue is resolved. 如果我将条件块与内容块一起包围,则此问题已解决。
{% block content%}
{% if form is defined %}
{{ form(form)}}
{% endif %}
{% end block %}
Thanks 谢谢
Did you try: 你试过了吗:
{% if form_to_be_renderer|length %}
{{ form(form_to_be_renderer) }}
{% endif %}
Twig documentation says: Twig文档说:
defined: 定义:
defined checks if a variable is defined in the current context. define检查在当前上下文中是否定义了变量。
empty: 空:
evaluates to true if the foo variable is null, false, an empty array, or the empty string. 如果foo变量为null,false,空数组或空字符串,则计算结果为true。
null: 空值:
null returns true if the variable is null. 如果变量为null,则null返回true。
So figure out, what exactly you want to check, depending on what value "form_to_be_rendered" can have. 因此,根据“ form_to_be_rendered”的值可以确定要检查的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.