post = { sizes: [ { w:100, title="hello"}, {w:200, title="bye"} ] }
假设我将它传递给我的Django模板。现在,我要显示的标题其中width = 200。我怎样才能做到这一点,没有做它蛮力方式:如何在Django模板中解析?
{{ post.sizes.1.title }}
我想这样做的解析方式。
post = { sizes: [ { w:100, title="hello"}, {w:200, title="bye"} ] }
假设我将它传递给我的Django模板。现在,我要显示的标题其中width = 200。我怎样才能做到这一点,没有做它蛮力方式:如何在Django模板中解析?
{{ post.sizes.1.title }}
我想这样做的解析方式。
一个简单的方法是使用过滤器模板标签。
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 %}
。
{% for i in post.sizes %}
{% if i.w == 200 %}{{ i.title }}{% endif %}
{% endfor %}