I have this Jinja2 template:
{% set input = 1 %}
{% set steps = [1, 2, 3, 4]|select("greaterthan", input) %}
{{ steps|list }}
{{ steps|first if steps|list|length > 0 else None }}
It prints:
[2, 3, 4]
None
Now I remove {{ steps|list }}
.
{% set input = 1 %}
{% set steps = [1, 2, 3, 4]|select("greaterthan", input) %}
{{ steps|first if steps|list|length > 0 else None }}
It prints nothing at all.
Then instead of {{ steps|list }}
I put {{ steps|first }}
.
{% set input = 1 %}
{% set steps = [1, 2, 3, 4]|select("greaterthan", input) %}
{{ steps|first }}
{{ steps|first if steps|list|length > 0 else None }}
Now it prints:
2
What is wrong with {{ steps|first if steps|list|length > 0 else None }}
that it behaves differently depending on what else I print?
{% set steps = [1, 2, 3, 4]|select("greaterthan", input) %}
is like a generator expression, basically the same as Python code like this:
steps = (select("greaterthan", item) for item in [1,2,3,4])
That is to say, steps
is a generator from which you can only pull out the next value until the values are exhausted. So, when you do {{ steps|list }}
at any point, you exhaust the generator and you can't iterate over the steps
variable again.
So, the translation of what happens in your jinja code could be approximately illustrated as follows:
>>> print(list(steps)) # exhausts the generator
[2, 3, 4]
>>> print(list(steps)) # no more values in the generator
[]
>>> print(len(list(steps))
0
What you probably wanted to do is first exhaust the generator into a list first and assign that value to the variable steps
.
I would guess the jinja syntax for this would be to just add |list
:
{% set steps = [1, 2, 3, 4]|select("greaterthan", input)|list %}