开发者

How do I do parsing in Django templates?

post = { sizes: [ { w:100, title="hello"}, {w:200, title="bye"} ] }

Suppose I pass that to my Django templates. Now, I want to display the title where width = 200. How can I do that, without doing it the brute-force way:

{{ post.sizes.1.title }}

I开发者_如何学C want to do it the parsed way.


A neat way to do it is with a filter template tag.

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

That should go in a templatetags package, say as postfilters.py, and {% load postfilters %} in your template.

Naturally you could also alter this to give you the correct sizes object and so you could do {% with post|detailsofwidth:200 as postdetails %}{{ postdetails.something }}, {{ postdetails.title }}{% endwith %}.


{% for i in post.sizes %}
    {% if i.w == 200 %}{{ i.title }}{% endif %}
{% endfor %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜