Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested For Loop in Jinja2

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.

like image 638
Rupert Avatar asked Jan 04 '16 03:01

Rupert


People also ask

How do I use for loops in my collection in Jinja2?

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.

What are the control structures in Jinja2?

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.

What are the limitations of the Jinja2 programming language?

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.

How to check if a variable exists in Jinja2?

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.


1 Answers

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.

like image 140
Rupert Avatar answered Oct 25 '22 00:10

Rupert