Search code examples
pythonflaskjinja2

How can I loop through 2 elements at the same time in jinja?


I have two elements and need to cylcle through both of them at the same time, but in JINJA(!). Naturally I tried to use zip() to go through both (list and dict) at the same time, but jinja does not allow that

 {% for (i, o) in zip(searches, e_links): %}
      <a href="/sid/{{ o }}">
      <div>{{ i.time_string }}</div>

Error:

jinja2.exceptions.UndefinedError: 'zip' is undefined

Is there another way for cycling through two items at the same time in jinja, or is it somehow possible to pass the zip() function to jinja?


Solution

  • I was able to resolve this if anybody in the future wants to know. You can simply zip() the two items before passing them to jinja like such:

    return render_template('results.html', packed=zip(searches, e_links))
    

    in the template then simply cycle through the zipped item:

    {% for i, o in packed: %}
    

    And yes, all in all it took me more than an hour to figure this one out.