【问题标题】:Twig if/else not working树枝如果/否则不工作
【发布时间】:2016-04-20 12:43:27
【问题描述】:

我不确定为什么我的代码没有执行。我知道它应该以这种方式工作,但现在发生的只是它不执行 else 部分。

在调试中,我知道 descriptions 不为 null,并且 descriptions 会显示给那些拥有它的人。

{% if descriptions is not null %}
{{ dump(descriptions) }}
    {% for description in descriptions %}
        <td>{{ description.productDesciption }}</td>
    {% endfor %}
{% else %}
    <td> 
        <a href = "{{ path('description') }}">Create a Description for this Product</a>
    </td>
{% endif %}

【问题讨论】:

  • 只是出于好奇,如果你使用这个 if 语句,你会得到任何不同的结果吗? {% if descriptions %}
  • 我想通了。我正在测试一个数组是否为空,所以我必须测试数组的长度/计数。
  • 啊,我明白了。很高兴你把它整理出来。 docs page 上有一个方便的值列表,用于说明哪些值也评估为真/假(它位于页面的最底部附近)。从技术上讲,一个空数组将在 if 语句中计算为 false,这有点方便。
  • 您还可以测试某些内容是否“非空”。这将检查变量是否为空、不是空字符串和空数组。

标签: php symfony twig


【解决方案1】:

您可以使用 for 语句的The else Clause 进行简化:

{% for description in descriptions %}
     <td>
        {{ description.productDesciption }}
     </td>
{% else %}
     <td> 
        <a href = "{{ path('description') }}">Create a Description for this Product</a>
    </td>
{% endfor %}

希望有帮助

【讨论】:

  • 一个小旁注:当您对非数组/可迭代/生成器类型进行 foreach 时,您会在 PHP 中收到警告。在树枝中,您不必担心这一点。如果你对 null 值执行 for/else,一切都会正常工作。
  • 我非常喜欢这个答案,我不知道你能做到这一点,它也对我有用,所以我会接受。
【解决方案2】:

您可以在for 循环中使用if

{% for description in descriptions if descriptions is not null %}
   <td>
    {{ description.productDesciption }}
   </td>
{% else %}
   <td> 
      <a href = "{{ path('description') }}">Create a Description for this Product</a>
   </td>
{% endfor %}

【讨论】:

  • 是的,您可以这样做,但请查看我对其他答案的评论。在这种情况下,如果检查是多余的。 for 中的 if 语句旨在用作您的集合上的过滤器。在您的示例中,如果在每个循环中都不是 null 而不是围绕它,它将执行此操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-04
  • 2014-04-13
  • 2016-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
相关资源
最近更新 更多