I have a list of dictionary
in python i.e.
我在python中有一个字典列表,即
listofobs = [{'timestamp': datetime.datetime(2012, 7, 6, 12, 39, 52), 'ip': u'1.4.128.0', 'user': u'lovestone'}, {'timestamp': datetime.datetime(2012, 7, 6, 12, 40, 32), 'ip': u'192.168.21.45', 'user': u'b'}]
I want to use all of the keys and value of listofobs
variable in a Django-template. For example:
我想在Django模板中使用listofobs变量的所有键和值。例如:
For the first iteration:
对于第一次迭代:
timestamp = 7 july 2012, 12:39 Am
ip = 1.4.128.0
user = lovestone
and for the second iteration :
并为第二次迭代:
timestamp = 7 july 2012, 12:40 Am
ip = 192.168.21.45
user = b
and so on ..
等等 ..
3 个解决方案
#1
9
for a in listofobs:
print str( a['timestamp'] ), a['ip'], a['user']
Will iterate over the list of dict's, then to use them in the template just wrap it in the needed django syntax and which is quite similar to regular python.
将遍历dict列表,然后在模板中使用它们只需将其包装在所需的django语法中,这与常规python非常相似。
#2
3
Django template syntax lets you loop over a list of dicts:
Django模板语法允许您循环遍历dicts列表:
{% for obj in listofobjs %}
timestamp = {{ obj.timestamp }}
ip = {{ obj.ip }}
user = {{ obj.user }}
{% endfor %}
All you need to is make sure listofobjs is in your context for rendering.
您需要做的就是确保listofobjs在您的上下文中进行渲染。
#3
2
Look at the examples for the built in for
template tag.
查看内置模板标记的示例。
Looping over items (your outer loop):
循环项目(你的外循环):
{% for obj in listofobjs %}
{# do something with obj (just print it for now) #}
{{ obj }}
{% endfor %}
And then loop over the items in your dictionary object:
然后循环遍历字典对象中的项:
{% for key, value in obj.items %}
{{ key }}: {{ value }}
{% endfor %}
#1
9
for a in listofobs:
print str( a['timestamp'] ), a['ip'], a['user']
Will iterate over the list of dict's, then to use them in the template just wrap it in the needed django syntax and which is quite similar to regular python.
将遍历dict列表,然后在模板中使用它们只需将其包装在所需的django语法中,这与常规python非常相似。
#2
3
Django template syntax lets you loop over a list of dicts:
Django模板语法允许您循环遍历dicts列表:
{% for obj in listofobjs %}
timestamp = {{ obj.timestamp }}
ip = {{ obj.ip }}
user = {{ obj.user }}
{% endfor %}
All you need to is make sure listofobjs is in your context for rendering.
您需要做的就是确保listofobjs在您的上下文中进行渲染。
#3
2
Look at the examples for the built in for
template tag.
查看内置模板标记的示例。
Looping over items (your outer loop):
循环项目(你的外循环):
{% for obj in listofobjs %}
{# do something with obj (just print it for now) #}
{{ obj }}
{% endfor %}
And then loop over the items in your dictionary object:
然后循环遍历字典对象中的项:
{% for key, value in obj.items %}
{{ key }}: {{ value }}
{% endfor %}