zip(list1, list2) in Jinja2?

John Salvatier picture John Salvatier · Mar 6, 2011 · Viewed 15.1k times · Source

I'm doing code generation in Jinja2 and I frequently want to iterate through two lists together (i.e. variables names and types), is there a simple way to do this or do I need to just pass a pre-zipped list? I was unable to find such a function in the docs or googling.

Answer

Garrett picture Garrett · Mar 7, 2011

Modify the jinja2.Environment global namespace itself if you see fit.

import jinja2
env = jinja2.Environment()
env.globals.update(zip=zip)
# use env to load template(s)

This may be helpful in separating view (template) logic from application logic, but it enables the reverse as well. #separationofconcerns