如何在django模板中迭代json字典? [英] How to iterate json dictionary in django template?

查看:289
本文介绍了如何在django模板中迭代json字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在django中是新的,现在我正在html页面中迭代一个json字典。我使用{{context}}显示从视图传递的字典,而context是用于在render_to_response中存储字典的变量。现在它被显示像

  [
{
pk:5,
模型:拍卖,
fields:{
username:1,
category:furniture,
description of $
end_date:2012-05-01 11:00:00,
start_price:100,
title:Table,
start_date:2012-03-04 11:24:11
}
}
]

我可以如何迭代这个字典来显示,如

  username:1 
类别:家具

任何人都可以帮助我

解决方案

除非您打算在Javascript中使用逻辑,否则不应将其转换为JSON。相反,在您的模板中,您可以在中迭代数组,并将该字典遍历用户名和类别键:

  {%for c in context%} 
< div> username:{{c.fields.username}}< / div>
< div> category:{{c.fields.category}}< / div>
{%endfor%}


I am new in django and now i am trying to iterate one json dictionary in html page. I am using the {{context}} for displaying the dictionary which is passed from the view and context is the variable used to store the dictionary in render_to_response. now it is diplayed like

[
  {
    "pk": 5, 
    "model": "Auction.newauction", 
    "fields": {
      "username": 1, 
      "category": "furniture", 
      "description": "Made of Wood", 
      "end_date": "2012-05-01 11:00:00", 
      "start_price": "100", 
      "title": "Table", 
      "start_date": "2012-03-04 11:24:11"
    }
  }
]

How I can iterate this dictionary to display like

username  : 1
category  : Furniture

Can anyone please help me

解决方案

You shouldn't "convert it to JSON" unless you're planning to have your logic in Javascript. Instead, in your template you could iterate over the array in a for loop and traverse the dictionary to the username and category keys:

{% for c in context %}
  <div>username: {{ c.fields.username }}</div>
  <div>category: {{ c.fields.category }}</div>
{% endfor %}

这篇关于如何在django模板中迭代json字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆