簡體   English   中英

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

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

我試過了:

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

在模板中:

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

上面的代碼將每個元素拆分為多個字符:

[

{

"

u

s

e

r

...

我在一個簡單的 Python 腳本中測試了上面的嵌套循環,它工作正常,但在 Jinja 模板中沒有。

數據:

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

在 Jinja2 迭代中:

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

筆記:

確保您有 dict 項目列表。 如果你得到UnicodeError可能是 dict 里面的值包含 unicode 格式。 這個問題可以在你的views.py解決。 如果 dict 是unicode對象,則必須編碼為utf-8

作為@Navaneethan 回答的旁注, Jinja2能夠為列表和詞典進行“常規”項目選擇,前提是我們知道詞典的鍵或列表中項目的位置。

數據:

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

在 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 %}

渲染輸出:

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

只是類似問題的附注(如果我們不想循環):

如何使用 Jinja 模板中的變量鍵查找字典?

下面是一個例子:

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

這可能是顯而易見的。 但是我們不需要花括號內的花括號。 直接的 python 語法有效。 (我發帖是因為我讓我感到困惑......)

或者,你可以簡單地做

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

但是找不到key的時候會報錯。 所以最好在 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 %}

在第一個答案中刪除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