Search code examples
pythonpython-3.xjinja2

How add index on a jinja template?


I'm passing list to my Jinja template through my Python code.

list = [123,232,334,412]

How can I add an indexing to the output ?

For example:

some text id1 = 123, id2 = 232, id3 = 334, id5 = 412

What I tried was:

some text {{ list | join(', id = ' ) }}

But the output contains no indexes:

some text id = 123, id = 232, id = 334, id = 412

Solution

  • you may use loop.index to get this.

    from jinja2 import Template
    s = "{% for element in elements %}id{{loop.index}} element {% endfor %}"
    
    template = Template(s)
    idx = template.render(elements=[123,232,334,412])
    
    print(idx)
    

    output

    id1 element id2 element id3 element id4 element