【问题标题】:How to iterate through a list of dictionaries in Jinja template?如何遍历 Jinja 模板中的字典列表?
【发布时间】:2014-10-11 22:44:53
【问题描述】:

我试过了:

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 模板中却不行。

【问题讨论】:

    标签: python dictionary flask iteration jinja2


    【解决方案1】:
    **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 %}
    

    【讨论】:

      【解决方案2】:

      数据:

      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

      【讨论】:

      • 可能是因为我使用的是更新版本的 jinja,但在我的情况下,我必须删除括号(改用 dict_item.items),否则会抛出 Could not parse the remainder: '()' from 'dict_item.items()'
      • 除了 TrakJohnson 的回答之外,我发现新的 jinja 使用 dict.key 而不是传统的 dict["key"] 索引字典。
      • @TrakJohnson:那么您没有使用 Jinja 模板,而是使用 Django 模板。你想阅读how to iterate through dictionary in a dictionary in django template?。 Django 模板语法类似,但又不一样。
      • @CameronHyde:Jinja 在所有版本中都支持对所有对象的属性和项目访问。请参阅Variables section of the template documentation。如果dict["key"] 不适合您,那么您使用的不是 Jinja 模板,而是 Django 模板。见Accessing dictionary by key in Django template
      • 如果您想以不同的方式使用字典中的每个项目 - 您不想循环访问键但仍想访问键,该怎么办?
      【解决方案3】:

      类似问题的补充说明(如果我们不想循环):

      如何在 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

      【讨论】:

        【解决方案4】:

        作为@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.
        

        【讨论】:

        • 如果 dict 的大小不固定并且会随时间变化,如何修改 jinja2 代码?
        【解决方案5】:
        {% for i in yourlist %}
          {% for k,v in i.items() %}
            {# do what you want here #}
          {% endfor %}
        {% endfor %}
        

        【讨论】:

        • {% for k,v in lis1.items() %} UndefinedError: 'unicode object' has no attribute 'items'
        • @user3089927 您的模板是否比您向我们展示的更多?这个解决方案是正确的。如果不是,则在执行您共享的代码时,lis 不是列表。
        • 我忽略了一件事。我必须替换列表字典中的双引号,当我这样做时,它显然会将字典列表转换为字符串。我将发布其他有关我面临的问题的问题。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-29
        • 2019-07-18
        • 1970-01-01
        • 1970-01-01
        • 2016-08-31
        • 2015-07-15
        • 2019-07-14
        相关资源
        最近更新 更多