Search code examples
pythonpython-3.xflaskjinja2

How can I iterate over my list in jinja2 flask app?


I have the following code:

{% extends "base.html" %}

{% block app_content %}

    <table class="table table-hover table-striped">

        <thead>
        <tr>
            <th style="text-align: center">Hostname</th>
            <th style="text-align: center">IP_address</th>
            <th style="text-align: center">uptime</th>
            <th style="text-align: center">location</th>
        </tr>
        </thead>
        <tbody>
            <ul>
            {% for canary in newlist %}
              <li>{{ canary }}</li>
            {% endfor %}
            </ul>
            

        </tbody>
    </table>

{% endblock %}

How do i make it so that each of my appended items from my python file are under each separate column?

Currently it just lists my list.

This is my return function

def canaries_up_time(results):

    results = results.json()
    #print(json.dumps(my_dict, indent=3))
    newlist = []
    for item in results['devices']:
        
        newlist.append(item.get("name"))
        newlist.append(item.get("uptime"))
        newlist.append(item.get("ip_address"))
        newlist.append(item.get("location"))

    return newlist

Solution

  • Put the canary items into a dictionary, pass that into the template and render it like so:

    {% for canary in newlist %}
        <tr>
            <td>{{canary.name}}</td>
            <td>{{canary.uptime}}</td>
            <td>{{canary.ip_address}}</td>
            <td>{{canary.location}}</td>
        </tr>
    {% endfor %}
    
    Edit, added snippet

    Where the dictionary keys are named like the variables above. Newlist now is a list of dictionaries, you could make it like this:

    newlist = []
    for item in results['devices']:
        newlist.append({'name':item.get("name"), 'ip_address':item.get("ip_address"), etc etc etc})