可能是一个简单的问题,但我已经搜索了一段时间,并且无法找到如何循环浏览字典中的所有项目并调用模板内的课程项目的答案
我尝试过使用自定义模板标签,但语法似乎与我想要的不一致。
这是我的代码:
data = [[OrderedDict([('token', 'XXXXXXXXXXXXXXX'), ('devices', [['Christmas Lights', 'XXXXXXXXXX'], ['Gold Beedrom Lamp', 'XXXXXXXX']])])], [[['5', 'off', 124], ['6', 'off', 124], ['7', 'off', 100], ['8', 'off', 124]]]]
#Dictionary and Class assignment
class LightStatus:
def __init__(self,id):
self.id = id
self.state = None
self.bri = None
def add_data(self,id,state,bri):
self.id = id
self.state = state
self.bri = bri
AllLights = dict()
for i in data[1]:
for light in i:
id = light[0]
state = light[1]
bri = light[2]
AllLights[id] = LightStatus(id)
AllLights[id].add_data(id,state,bri)
我希望在模板中提供什么:
#What I want to do in the template
for i in AllLights:
print(AllLights[i].id)
print(AllLights[i].state)
print(AllLights[i].bri)
return render(request, 'file.html', 'lights': AllLights)
#What I've tried
{% for light in lights %}
{% for i in light %}
{{lights.light.id}} #light being the variable from above.
{% endfor %}
{% endfor %}
我也尝试过使用自定义模板代码:
from django import template
register = template.Library()
@register.filter
def lights(LightDict, i):
return LightDict[int(i)]
#template
{{ AllLights|lights.forloop.counter0 }}
总结一下我想做什么。我想将AllLights
dict传递给我的模板,然后循环浏览所有密钥,并为每个密钥调用id
,state
和bri
。
更新
有人问我在渲染之前打印(AllLights)会发生什么:
{'5': <dashboard.views.LightStatus object at 0x106f016a0>, '6': <dashboard.views.LightStatus object at 0x106f01320>, '7': <dashboard.views.LightStatus object at 0x106f01ac8>, '8': <dashboard.views.LightStatus object at 0x106f014e0>}
答案 0 :(得分:1)
你(正确)使用有序的dict维护顺序,所以假设该dict中的顺序是所需的顺序,你应该能够在模板中迭代你的有序字典values
:
{% for light in all_lights.values %}
{{ light.id }}
{{ light.state }}
{{ light.bri }}
{% endfor %}