【问题标题】:How do I do parsing in Django templates?如何在 Django 模板中进行解析?
【发布时间】:2010-12-03 02:29:58
【问题描述】:
post = { sizes: [ { w:100, title="hello"}, {w:200, title="bye"} ] }
假设我将它传递给我的 Django 模板。现在,我想显示宽度 = 200 的标题。我该如何做到这一点,而不是用蛮力的方式:
{{ post.sizes.1.title }}
我想按照解析的方式来做。
【问题讨论】:
标签:
python
django
templates
list
dictionary
【解决方案1】:
一个巧妙的方法是使用过滤器模板标签。
from django.template import Library
register = Library()
@register.filter('titleofwidth')
def titleofwidth(post, width):
"""
Get the title of a given width of a post.
Sample usage: {{ post|titleofwidth:200 }}
"""
for i in post['sizes']:
if i['w'] == width:
return i['title']
return None
这应该放在templatetags 包中,例如在您的模板中postfilters.py 和{% load postfilters %}。
当然,您也可以更改它以提供正确的sizes 对象,这样您就可以使用{% with post|detailsofwidth:200 as postdetails %}{{ postdetails.something }}, {{ postdetails.title }}{% endwith %}。
【解决方案2】:
{% for i in post.sizes %}
{% if i.w == 200 %}{{ i.title }}{% endif %}
{% endfor %}