I am making a nested for loop in Jinja / Python Flask.
If I hard code the values, then it works fine. Am I missing something in the Jinja template?
<table class="table table-striped">
<tr>
{% for column in Columns %}
<td>{{ column }}</td>
{% endfor %}
</tr>
{% for row in rows %}
<tr>
{% for column in Columns %}
<td>{{ row.column }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
By the way, the output is nothing when it is not hardcoded.
Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %}. This is very similar to how you'd loop over an iterable in Python. Here my_item is a loop variable that will be taking values as we go over the elements.
Control structures In Jinja2 loops and conditionals come under name of control structures, since they affect flow of a program. Control structures use blocks enclosed by {% and %} characters.
In developing the j2 (the Jinja2 templating language) logic to do things like calculate bandwidth figures, we ran into some limitations. Mainly the ability to have a variable’s value accessible outside of the loop that is currently being run.
If you simply want to check if the variable exists then is defined test, which we'll look at shortly, is usually a better choice. Tests in Jinja2 are used with variables and return True or False, depending on whether the value passes the test or not. To use this feature add is and test name after the variable.
Figured it out...
<table class="table table-striped">
<tr>
{% for column in Columns %}
<td>{{ column }}</td>
{% endfor %}
</tr>
{% for row in rows %}
<tr>
{% for column in Columns %}
<td>{{ row[column] }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
The only changed needed was to change {{ row.column }}
to {{ row[column] }}
on line 11.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With