【问题标题】:How to pass list containing dictionary in html template and access its values如何在html模板中传递包含字典的列表并访问其值
【发布时间】:2021-10-22 03:23:06
【问题描述】:

在 django 我有这个列表

my_list=[{'id':1,'username':'sometext'},{'id':2,'username':'someothertext'}]

我正在将此列表传递到模板中

   return render(request,'template.html',{'mylist':my_list})

这是我的模板.html

               {% for i in mylist.items %}
                   <tr>
                                        
                      <td>{{ mylist.id }}</td>
                      <td>{{ mylist.username }}</td>
                                 
                   </tr>
               {% endfor %}

但是这样做我没有得到 id 和 username 的值。

【问题讨论】:

  • 使用&lt;td&gt;{{ i.id }}&lt;/td&gt;而不是使用&lt;td&gt;{{ mylist.id }}&lt;/td&gt;

标签: python html python-3.x django


【解决方案1】:

mylist 是一个列表,而不是字典,所以你应该用以下方式枚举:

{#     no .items &downarrow;    #}
{% for item in mylist %}
  <tr>
    {# use item &downarrow; #}
    <td>{{ item.id }}</td>
    <td>{{ item.username }}</td>
  </tr>
{% endfor %}

【讨论】:

    猜你喜欢
    • 2018-09-11
    • 2020-02-28
    • 2021-10-17
    • 2016-02-29
    • 2015-08-18
    • 2012-01-05
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多