How to get index of the element in the list in Jinja

There is no filter, only method

George Shuklin
OpsOps
Nov 25, 2021

--

Duality of python methods VS jinja filters is maddening. There is a problem: I need to get index of the first occurrence of the element in a list.

python

>>> [1,2,3,3,1,2].index(3)
2

Jinja2

… nothing

But!

'{{ [1,2,3,3,1,2].index(3) }}'
...
2

Filters VS methods

I find this the most infuriating. Jinja is a sub-language with some specific notation (filters), and, generally, filters should be used for data manipulation.

But you still can use Python methods and only methods. If you can call this by dot, it’s good to go. If you need to use it as a function, you need a filter.

You can’t call int(foo), you need foo|int, but you must use foo.index, not the foo|index .

This amazing persistent sometimes consistency…

--

--

George Shuklin
OpsOps

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.