[英]Iterate and format dictionary returned by template filter
我正在尝试在我的 Django 应用程序中显示有关图像的元数据。 元数据从图像的 exif 标头中读取并存储在以图像为键的字典中,并通过过滤器返回到模板。 在我的模板中,我显示图像,并希望显示该图像的格式化元数据。 到目前为止,我只能让它显示该图像的字典(例如{'key1': 'value', 'key2', 'value'}
)。 我希望它看起来像key1: value, key2: value
。
#template.html
{% block content %}
{% for image in images %}
{{ exif|get_item:image }}
<p><img src="{{ image.image.url }}" width="500" style="padding-bottom:50px"/></p>
{% endfor %}
{% endblock %}
#views.py
def image_display(request):
images = image.objects.all()
exif = {}
for file in images:
cmd = 'exiftool ' + str(file.image.url) + ' -DateTimeOriginal -Artist'
exifResults = (subprocess.check_output(cmd)).decode('utf8').strip('\r\n')
exif[file] = dict(map(str.strip, re.split(':\s+', i)) for i in exifResults.strip().splitlines() if i.startswith(''))
context = {
'images': images,
'exif': exif,
}
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
return render(request, 'image_display.html', context=context)
我以为我可以在模板中执行{% for key, value in exif|get_item:image.items %}
,但这会返回错误:
VariableDoesNotExist at /reader/image_display
Failed lookup for key [items] in <image: image1>
有没有一种方法可以格式化过滤器返回的字典或遍历它以便我可以格式化每个键和值对?
在我看来,您正在使用这个问题的自定义过滤器实现: Django 模板如何使用变量查找字典值,但您需要额外的步骤来格式化特定键,因为它是字典。
为什么不创建另一个可以返回您想要的格式的字典的过滤器?
像这样的东西:
@register.filter
def get_item_formatted(dictionary, key):
tmp_dict = dictionary.get(key, None)
if tmp_dict and isinstance(tmp_dict, dict):
return [[t_key, t_value] for t_key, t_value in tmp_dict.items()]
return None
这将返回[key, value]
对或None
的列表列表。
您可以在模板中迭代它:
{% block content %}
{% for image in images %}
{% for pair in exif|get_item_formatted:image %}
// Do what you need with the pair.0 (key) and pair.1 (value) here.
{% endfor %}
{% endfor %}
{% endblock %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.