symfony 2.8和twig:未定义的变量

时间:2016-04-29 17:34:27

标签: php symfony twig

我有这段代码:

{% block vich_image_widget %}
    {% spaceless %}
        <div class="vich-image">
            {{ dump() }}
            {{ form_row(form.file) }}
            {% if form.delete is defined %}
                {{ form_row(form.delete) }}
            {% endif %}
            {{ download_uri }}
            {% if download_uri is defined and download_uri %}
                <a href="{{ download_uri }}"><img src="{{ download_uri | imagine_filter('my_thumb')}}" alt="" /></a>
            {% endif %}
            {% if show_download_link and download_uri is defined and download_uri%}
                <a href="{{ download_uri }}">{{ 'download'|trans({}, 'VichUploaderBundle') }}</a>
            {% endif %}
        </div>
    {% endspaceless %}
{% endblock %}

这给了我这个错误:

Variable "download_uri" does not exist in offerte/edit.html.twig at line 21

第21行是:{{ download_uri }}

但为什么我会收到此错误?,twig在第22行使用download_uri而没有任何问题。

2 个答案:

答案 0 :(得分:1)

在第22行中它仅在download_uri存在时使用,这就是为什么你在第21行得到错误它明确地说这个变量不存在,因为你没有将它传递给这个tmpl。

{% if download_uri is defined %}
{{download_uri}}
{% endif %}

答案 1 :(得分:0)

在第21行中,您没有检查变量是否可用,因此您需要将其放在if块中:

 {% if download_uri is defined and download_uri %}
     {{ download_uri }}
     <a href="{{ download_uri }}"><img src="{{ download_uri | imagine_filter('my_thumb')}}" alt="" /></a>
 {% endif %}

也是这样:

{% if download_uri is defined and download_uri %}

应如下所示:

{% if download_uri is defined and download_uri is not empty %}