0

所以我一直在努力解决这个问题。

在 PHP 中,首先说出 isset($var) 和 $var == 就足够了,它不会抱怨我试图比较不存在的东西。

显然,在 TWIG 中这还不够。

现在,为什么这不起作用?我首先运行 if 来检查 entity.container 是否已设置,如果没有,请不要通过该块。

看来 TWIG 无论如何都必须遍历所有代码。所以,我有这个实体并不总是有一个容器(entity.container)集,那么我应该怎么做呢?因为当我运行此代码时,TWIG 只是抱怨我有一个 if 语句,当 entity.container 不存在时,我尝试去 entitiy.container.containerType 。

{% if entity.container is defined %}
    {% if entity.trash == false and entity.container.containerType.name =='Module' %}
        <form action="{{ path('deleteContent', { 'id': entity.id }) }}" method="post" onsubmit="return confirm('Bekräfta att du vill radera detta innehåll? Detta går inte att ångra.')">
            {{ form_widget(delete_form) }}
            <button type="submit" style="color:red;">Radera permanent</button>
        </form>
    {% elseif entity.trash == false and entity.container.containerType.name !='Module' %}
        <form action="{{ path('deleteContent', { 'id': entity.id }) }}" method="post">
            {{ form_widget(delete_form) }}
            <button type="submit" style="color:red;">Flytta till papperskorgen</button>
        </form>
    {% elseif entity.trash == true and entity.container != null %}
        <form action="{{ path('restoreContent', { 'id': entity.id }) }}" method="post">
            {{ form_widget(delete_form) }}
            <button type="submit" style="color:red;">Återställ till ursprunglig plats</button>
        </form>
    {% else %}
        För att återställa detta innehåll måste du först välja en plats för det.
    {% endif %}
{% else %}
hehe
{% endif %}
4

1 回答 1

3

我认为在您的情况下, entity.container已定义但未设置,可能为空。已定义变量与空变量或空变量之间存在差异。

所以第一个 if 语句被检查并允许解析里面的逻辑。

要检查是否设置了变量,您必须使用

{% if entity.container %}

或者干脆使用“不为空”,

{% if entity.container is not null %}

两者都具有应定义变量的条件,否则您将收到错误“Item or Object”container.whateverYouWant” for “entity” does not exist ...”

于 2012-11-03T23:56:13.763 回答