简体   繁体   中英

FLASK: Creating table in JINJA from python dict

I'm trying to build a table in HTML from a dict.

I have the following data:

alternativas = { 'attribute1':[val1, val2, val3] , 'attribute2':[val4, val5]}

and I want to display a table like:

attribute1         attribute2
val1                val4
val2                val5
val3

I have tried with:

{% for dict_item in alternativas %}
        <tr>
           {% for value in alternativas.values() %}
                {% for item in value %}
                    <td> {{ item }} </td>
                {% endfor %}
           {% endfor %}
        </tr>
 {% endfor %}

But I can't get the results I want.

You right code should be (amended line is commented):

{% for dict_item in alternativas %}
        <tr>
           {% for value in alternativas[dict_item] %} #amended line
                {% for item in value %}
                    <td> {{ item }} </td>
                {% endfor %}
           {% endfor %}
        </tr>
 {% endfor %}

or more concisely:

{% for key, value in alternativas %}
            <tr>
               {% for item in value %}
                        <td> {{ item }} </td>
               {% endfor %}
            </tr>
     {% endfor %}

Not sure if it works properly though, as jinja looping through dictionaries is sometimes tricky

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