【问题标题】:twig: check if all included arrays in an object are emptytwig:检查对象中所有包含的数组是否为空
【发布时间】:2016-09-14 16:05:13
【问题描述】:

我有一个包含多个命名数组对象的 twig 变量,如下所示:

{{ dump(trashbin) }}

输出:

array:2 [
  "Campaign" => []
  "ClientBudget" => []
]

我目前正在做的是检查包含的数组的长度是否为 0:

{% if trashbin.Campaign|length == 0 and trashbin.ClientBudget|length == 0 %}
Nothing to undelete. Trashbin empty
{% endif %}

将来,我无法预见名称的任意数量的命名数组可能会添加到该列表中。

如何简化和概括检查所有包含的数组是否为空?在这种情况下,我想向用户显示一条特殊消息。

【问题讨论】:

    标签: twig


    【解决方案1】:

    如果您不希望控制器/模型中的逻辑,则必须为此使用flag

    {% set has_trash = false %}
    {% for trash in trashbin if not trash is empty %}
        {% set has_trash = true %}
    {% endfor %}
    
    {% if not has_trash %}
       Nothing to delete
    {% endif %}
    

    twigfiddle

    【讨论】:

    • 那么,你有你的答案,因为这纯粹是twig
    • 误读了您的评论。这正是我所希望的。谢谢!
    【解决方案2】:
    {% if trashbin|filter(v => v is not empty) is not empty %}
    

    也会起作用的。

    【讨论】:

    • 完美运行,谢谢!
    猜你喜欢
    • 2020-06-07
    • 2021-05-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2019-06-05
    • 1970-01-01
    相关资源
    最近更新 更多