使用Jinja for循环遍历字典列表

时间:2019-02-25 11:14:21

标签: list dictionary for-loop html-table jinja2

我的Jinja for循环会以正确的次数打印列表中的第一个值,但只是没有获得正确的值。说

列表包含

harry, male, 1994
samuel, male, 1998

它将打印

harry, male, 1994
harry, male, 1994

我在这里做什么错了?

    {% extends "layout.html" %}

{% block main %}
    <table style="width:100%">
        <tr>
            <th> Name </th>
            <th> Nationality </th>
            <th> Gender </th>
            <th> Study </th>
            <th> Email </th>
            <th> Password </th>
        </tr>
        {% for name, nationality, gender, study, email, password in students %}
        <tr>
            <td> {{ name }} </td>
            <td> {{ nationality }} </td>
            <td> {{ gender }} </td>
            <td> {{ study }} </td>
            <td> {{ email }} </td>
            <td> {{ password }} </td>
        {% endfor %}
        </tr>

</table>

{% endblock %}

1 个答案:

答案 0 :(得分:0)

答案是:

{% extends "layout.html" %}

{% block main %}
    <table style="width:100%">
        <tr>
            <th> Name </th>
            <th> Nationality </th>
            <th> Gender </th>
            <th> Study </th>
            <th> Email </th>
            <th> Password </th>
        </tr>
        {% for student in students %}
        <tr>
            <td> {{ student['name'] }} </td>
            <td> {{ student['nationality'] }} </td>
            <td> {{ student['gender'] }} </td>
            <td> {{ student['study'] }} </td>
            <td> {{ student['email'] }} </td>
            <td> {{ student['password'] }} </td>
        {% endfor %}
        </tr>

</table>

{% endblock %}

同时确保csv文件的第一行是:

1.name,nationality,gender,study,email,password