Home > Enterprise >  How can i iterate through my list in jinja2 flask app?
How can i iterate through my list in jinja2 flask app?

Time:08-19

I have the following code:

{% extends "base.html" %}

{% block app_content %}

    <table >

        <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 colomn?

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

CodePudding user response:

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})

CodePudding user response:

In your .py you need to pass newlist as a return:

@app.route("/")
def index():
    newlist = ['a', 'b', 'c']
    return render_template('index.html', newlist=newlist)

Let me know if this solves your problem.

CodePudding user response:

If you need your items in columns, you need "tr" and "td" inside the "tbody", not the "li" tag. And I don't know, how your "newlist" looks like, if you can post that, someone might give you a better answer.

  • Related