简体   繁体   English

如何遍历 Jinja 模板中的字典列表?

[英]How to iterate through a list of dictionaries in Jinja template?

I tried:我试过了:

list1 = [{"username": "abhi", "pass": 2087}]
return render_template("file_output.html", list1=list1)

In the template:在模板中:

<table border=2>
  <tr>
    <td>
      Key
    </td>
    <td>
      Value
    </td>
  </tr>
  {% for dictionary in list1 %}
    {% for key in dictionary %}
      <tr>
        <td>
          <h3>{{ key }}</h3>
        </td>
        <td>
          <h3>{{ dictionary[key] }}</h3>
        </td>
      </tr>
    {% endfor %}
  {% endfor %}
</table>

The above code is splitting each element into multiple characters:上面的代码将每个元素拆分为多个字符:

[

{

"

u

s

e

r

...

I tested the above nested loop in a simple Python script and it works fine but not in Jinja template.我在一个简单的 Python 脚本中测试了上面的嵌套循环,它工作正常,但在 Jinja 模板中没有。

Data:数据:

parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]

in Jinja2 iteration:在 Jinja2 迭代中:

{% for dict_item in parent_list %}
   {% for key, value in dict_item.items() %}
      <h1>Key: {{key}}</h1>
      <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}

Note:笔记:

Make sure you have the list of dict items.确保您有 dict 项目列表。 If you get UnicodeError may be the value inside the dict contains unicode format.如果你得到UnicodeError可能是 dict 里面的值包含 unicode 格式。 That issue can be solved in your views.py .这个问题可以在你的views.py解决。 If the dict is unicode object, you have to encode into utf-8 .如果 dict 是unicode对象,则必须编码为utf-8

As a sidenote to @Navaneethan 's answer, Jinja2 is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.作为@Navaneethan 回答的旁注, Jinja2能够为列表和词典进行“常规”项目选择,前提是我们知道词典的键或列表中项目的位置。

Data:数据:

parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]

in Jinja2 iteration:在 Jinja2 迭代中:

{% for dict_item in parent_dict %}
   This example has {{dict_item['A']}} and {{dict_item['B']}}:
       with the content --
       {% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}

The rendered output:渲染输出:

This example has val1 and val2:
    with the content --
    1.1 and 2.2.

This example has val3 and val4:
   with the content --
   3.3 and 4.4.
{% for i in yourlist %}
  {% for k,v in i.items() %}
    {# do what you want here #}
  {% endfor %}
{% endfor %}

Just a side note for similar problem (If we don't want to loop through):只是类似问题的附注(如果我们不想循环):

How to lookup a dictionary using a variable key within Jinja template?如何使用 Jinja 模板中的变量键查找字典?

Here is an example:下面是一个例子:

{% set key = target_db.Schema.upper()+"__"+target_db.TableName.upper() %}
{{ dict_containing_df.get(key).to_html() | safe }}

It might be obvious.这可能是显而易见的。 But we don't need curly braces within curly braces.但是我们不需要花括号内的花括号。 Straight python syntax works.直接的 python 语法有效。 (I am posting because I was confusing to me...) (我发帖是因为我让我感到困惑......)

Alternatively, you can simply do或者,你可以简单地做

{{dict[target_db.Schema.upper()+"__"+target_db.TableName.upper()]).to_html() | safe }}

But it will spit an error when no key is found.但是找不到key的时候会报错。 So better to use get in Jinja.所以最好在 Jinja 中使用get

**get id from dic value. I got the result.try the below code**
get_abstracts = s.get_abstracts(session_id)
    sessions = get_abstracts['sessions']
    abs = {}
    for a in get_abstracts['abstracts']:
        a_session_id = a['session_id']
        abs.setdefault(a_session_id,[]).append(a)
    authors = {}
    # print('authors')
    # print(get_abstracts['authors'])
    for au in get_abstracts['authors']: 
        # print(au)
        au_abs_id = au['abs_id']
        authors.setdefault(au_abs_id,[]).append(au)
 **In jinja template**
{% for s in sessions %}
          <h4><u>Session : {{ s.session_title}} - Hall : {{ s.session_hall}}</u></h4> 
            {% for a in abs[s.session_id] %}
            <hr>
                      <p><b>Chief Author :</b>  Dr. {{ a.full_name }}</p>  
               
                {% for au in authors[a.abs_id] %}
                      <p><b> {{ au.role }} :</b> Dr.{{ au.full_name }}</p>
                {% endfor %}
            {% endfor %}
        {% endfor %}

IN THE FIRST ANSWER remove the parantheses in dict items AND try again !!在第一个答案中删除dict项目中的括号并重试!

{% for dict_item in parent_list %}
   {% for key, value in dict_item.items %}
      <h1>Key: {{key}}</h1>
      <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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