Jinja2 multiple variables in same for loop

10,773

I usually zip them up into a list of tuples in the view function. Make sure the teams and wins are sorted correctly beforehand.

team_info = zip(teams, wins)

And then you can access the tuples as you iterate over the list in the template

{% block content %}
{% for team, win in team_info %}
    <div>{{ team[0] }} record: {{ wins[1] }}</div>
    <div>{{ team[1] }} and {{ team[2] }}</div>
    <div>{{ team[3] }}</div>
{% endfor %}
Share:
10,773

Related videos on Youtube

Prokes
Author by

Prokes

Updated on September 15, 2022

Comments

  • Prokes
    Prokes over 1 year

    I would like to populate the same section of a Jinja2 for loop with data from 2 separate SQL queries using Python / Webapp2 / Jinja2.

    Specifically, I am storing team info in a variable called "team" and score info in a variable called "wins". I need to position some data from the wins variable directly after data from the team variable but cannot figure out how to do this within a for loop.

    Here is a simplified version of what I am trying to achieve:

    {% block content %}
    {% for team in team %}
            <div>{{ team[0] }} record: {{ wins[1] }}</div>
            <div>{{ team[1] }} and {{ team[2] }}</div>
            <div>{{ team[3] }}</div>
    {% endfor %}
    {% endblock %}
    

    What is the best way to do this? I need to get that "wins" variable called but cannot determine how. Any help is appreciated.

  • Prokes
    Prokes almost 11 years
    Thank you very much - this worked. Concise and thorough, cheers.