connexo connexo - 1 month ago 5x
Twig Question

twig: check if all included arrays in an object are empty

I have a twig variable containing a number of named array objects like this:

{{ dump(trashbin) }}


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

What I'm currently doing is checking if the contained arrays have a length of 0:

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

In the future, any number of named arrays with names I cannot foresee may be added to that list.

How can I simplify and generalize the check if all contained arrays are empty? I want to display a special message to the user in that case.


If you don't want the logic inside your controller/model you'll have to use a flag for this :

{% 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 %}