2010-12-03 30 views
0
post = { sizes: [ { w:100, title="hello"}, {w:200, title="bye"} ] } 

これを私のDjangoテンプレートに渡すとします。今、私は、ブルートフォース方法でそれをやってなくて、幅= 200は、どのように私はそれを行うことができますタイトルを表示したい:私はそれを解析された方法をやりたいDjangoテンプレートの解析はどのように行いますか?

{{ post.sizes.1.title }} 

答えて

2

これを行うには、フィルタテンプレートタグが必要です。 templatetagsパッケージに行くべき

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 

postfilters.py、およびテンプレートで{% load postfilters %}と言います。

当然、あなたは正しいsizesオブジェクトを与えるためにこれを変更することもできるので、{% with post|detailsofwidth:200 as postdetails %}{{ postdetails.something }}, {{ postdetails.title }}{% endwith %}を行うことができます。

0
{% for i in post.sizes %} 
    {% if i.w == 200 %}{{ i.title }}{% endif %} 
{% endfor %} 
関連する問題