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 want to do it the parsed way.

Answers


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 %}.


Need Your Help

store object file when phone is shutted down and retrieve the file when the phone is rebooted

android android-file

I have saved an object of a class in a file in my application, when the phone shuts down, what happens to the file? I think, the file get lost. because after reboot my phone, I get null values(whic...

Send android sensor data over UDP socket

android sockets udp sensor

I'm writing an app to get sensor data from my Android phone (GPS position, accelerometer, orientation) and send the data over UDP to a server (I plan to use Python for that, by the way).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.