Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 multiple variables in same for loop

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.

like image 547
Prokes Avatar asked Jul 16 '26 18:07

Prokes


1 Answers

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 %}
like image 115
Michael Davis Avatar answered Jul 19 '26 10:07

Michael Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!