Count non-null values in a sequence


#1

I want to know the number of non-null values in a sequence. For example in:

['foo', null, null, 1, 'bar']

there are 3 non-null values. I tried looping over it like this:

{% set non_null_count = 0 %}
{% for v in my_sequence %}
  {% if v != null %}
    {% set non_null_count = non_null_count + 1 %}
  {% endif %}
{% endfor %}
{{ non_null_count }}

but the non_null_count falls out of scope when the for loop ends (a known hubl limitation I've since found out), so this prints 0 not 3.

I've also tried using export_to_template_context, but I can't figure out how to increment a value setting a value to:

{% text "non_null_count" value=widget_data.non_null_count.value|int + 1, no_wrapper=True export_to_template_context=True %}

(and have tried similar but various attempts at different syntax) but this doesn't work.

Can anyone suggest a workaround?

EDIT:
I found a solution that leaks the variable to an outer scoped array by using an if.
It feels quite hacky, but hey...

{% set non_null_count_array = [] %}
{% for v in my_sequence %}
  {% if v != null %}
    {% if non_null_count.append('1') %}{% endif %}
  {% endif %}
{% endfor %}
{{ non_null_count_array|length }}

The hack part is this part:

{% if non_null_count.append('1') %}

If you instead try to just append (without the if) it doesn't work. By using the if, the condition check leaks the variable to your outer scope array, which can then be used as required. The '1' can be anything in this example.

Hope this helps someone else.