acanthis acanthis - 3 months ago 33
Twig Question

Symfony3 Variable does not exist in including template

I get the following error: Variable "file" does not exist.

The included template Contractor:file.html.twig looks like this:

{{ dump(file) }}


The main template form.html.twig looks like this:

{% extends '::base.html.twig' %}
{% form_theme form 'NaSoftEdmBundle:Form:fields.html.twig' %}

...

{% block files %}
{% for file in form.files %}
{{ include('NaSoftEdmBundle:Contractor:file.html.twig', {'file': file}) }}
{% endfor %}
{% endblock %}


Controller:

public function editAction(Request $request, Contractor $contractor)
{
...
return $this->render('NaSoftEdmBundle:Contractor:form.html.twig', array(
'form' => $form->createView(),
));
}





But when I try to display a variable inside the main template file (form.html.twig), the variable becomes available:

{% for file in form.files %}
{{ dump(file) }} {# it work! #}
{% endfor %}


ContractorFile {#499 ▼
-id: 154
-uploadedFile: null
-name: "57c6d217d9a92.jpg"
-origName: "1471590585502.jpg"
-path: "/contractor/docs/files/2/335"
-size: 153536
-mimeType: "image/jpeg"
-updateDate: DateTime {#496 ▶}
-contractor: Contractor {#370 ▶}
}


command
php app/console cache:clear
did not help

Answer

The problem was that I was before starting the cycle "for" included the same template for attribute data-prototype:

data-prototype="{% filter escape %} 
     {% include 'NaSoftEdmBundle: Contractor: file.html.twig' with { '_form':form.files.vars.prototype} %}
{% endfilter %}"

I've created for the attribute "data-prototype" new template and it worked.

data-prototype="{% filter escape %} 
     {% include 'NaSoftEdmBundle: Contractor: filePrototype.html.twig' with { 'file':_form.files.vars.prototype} %}
{% endfilter %}"

This has been implemented to customize the template collection