简体   繁体   中英

How can i iterate through 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 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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM