[英]How do I iterate dictionary with lists as values in Django template?
我有一个列表作为值的字典(截断给你一个例子):
图像文件:
for prop in context['results'][0]:
imageFolderPath ='./media/uploaded/prop_images/' + prop.property_ID
if os.path.isdir(imageFolderPath):
imageFileList[prop.property_ID] = [f for f in listdir(imageFolderPath) if isfile(join(imageFolderPath, f))]
context['imageFiles'] = [imageFileList]
这是我直接在模板中打印时显示的内容:
[{'R01': ['02secparking27.jpg', '10-2017-ff-detail-1200x627.jpg', '1200x820.jpg', '12539233_web1_180704-VMS-parking-lot.jpg', '16.12.01-519196006.jpg',],
'R02': ['asdasd.jpg','12131asad.jpg','asdasdasd.jpg']}]
在模板中,我试图通过迭代来访问图像名称,但我没有得到任何值。
{% for keys,values in imageFiles %}
{% for x in values %}
<p> {{X}} </p>
{% endfor %}
{% endfor %}
出错
“需要 2 个值才能在 for 循环中解压;得到 9 个。”
我还按照其他帖子中的建议尝试了 imageFiles.items ,但它似乎不起作用。
我究竟做错了什么? 在这里绞尽脑汁。
所以,你正在传递:
context['imageFiles'] = [imageFileList]
这很令人困惑,没有充分的理由。 你所说的imageFileList
不是一个列表,而是一个字典。 然后,您传递给模板的是一个具有单个元素的列表,即该字典。
修复:传入字典(如果您将imageFileList
的名称更改为不那么令人困惑的名称会更好):
context['imageFiles'] = imageFileList
在您的模板中:
{% for key, value in imageFiles.items %}
{% for x in values %}
<p> {{x}} </p>
{% endfor %}
{% endfor %}
假定
dct = your input dictionary
代码:
[value for keys, values in dct.items() for value in values]
将为您提供以下文件名列表:
['02secparking27.jpg',
'10-2017-ff-detail-1200x627.jpg',
'1200x820.jpg',
'12539233_web1_180704-VMS-parking-lot.jpg',
'16.12.01-519196006.jpg',
'asdasd.jpg',
'12131asad.jpg',
'asdasdasd.jpg']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.