1
votes

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,

3
Just to rule out obvious things, that's the only place you use that variable, right? So we can be sure it's not being used somewhere else without the if <var> is defined guardmzulch
Yeah. I mean the var is only used inside the conditional block of courseCarles
The second line of your code (call to form function) should use expression delimiters ({{ }}) rather than tag delimiters ({% %}) though I would expect Twig_Error_Syntax instead of Twig_Error_Runtime if that were the primary issuemzulch
You are right. It's my fault when copying the code. Edited on the OPCarles
Which line is number three? The one with if or form()?Kaivosukeltaja

3 Answers

2
votes

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

0
votes

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.

0
votes

Did you try:

{% if form_to_be_renderer|length %}
    {{ form(form_to_be_renderer) }}
{% endif %}