简体   繁体   中英

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. 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. 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.

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.

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.

EDIT

I forgot to post that there is a {% block content %} inside the conditional block which causes the issue. 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.

{% 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. 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:

defined:

defined checks if a variable is defined in the current context.

empty:

evaluates to true if the foo variable is null, false, an empty array, or the empty string.

null:

null returns true if the variable is null.

So figure out, what exactly you want to check, depending on what value "form_to_be_rendered" can have.

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