Feed Sign in with OpenID OpenID

Simon Willison’s Weblog

Django snippets: "for" template tag with support for "else" if array is empty. A neat solution to a common pattern; I’d personally like to see this included in Django proper.

Tagged , , ,

7 comments

  1. Yeah, I also would love to see this in Django :) Ticket #6398

    Jannis Leidel - 16th January 2008 23:22 - #

  2. Agreed, it's a very common pattern in my code.

    Jason Davies - 17th January 2008 00:12 - #

  3. I thought it was cool myself, but the alternative isn't very difficult (just adding an if block around the for loop).

    Rob Hudson - 17th January 2008 01:01 - #

  4. Yes, but I prefer a single {% else %} over an extra {% if %}...{% endif %} block to keep track of.

    Jason Davies - 17th January 2008 02:07 - #

  5. While I found it initially interesting, I realize I wouldn't use it often :

    The comon pattern is to have a <ul/li> with the {% for %} loop inside of the <ul>, so I generally tend to replace the whole list with a sentence (or remove it and the <h2> tag altogether), as a <ul/li> with only one element telling there is nothing isn't very adapted. (Hope I'm clear enough)

    So I wouldn't use something ofter that can be replaced by something easy (if+for) : one obvious way to do it.

    Ikshefem - 17th January 2008 08:48 - #

  6. That's *not* how the for-in-else construct works in Python, though, so maybe a different name for the empty clause would be a good idea?

    Fredrik - 17th January 2008 12:00 - #

  7. for/else works differently in python, and this would cause much confusion. Personally, I think this should be semantics in python, but it's too late for that.

    I'm up for {% default %} or {% empty %} as alternatives, though

    Moof - 17th January 2008 14:10 - #

Sign in with OpenID

Auto-HTML: Line breaks are preserved; URLs will be converted in to links.

Manual XHTML: Enter your own, valid XHTML. Allowed tags are a, p, blockquote, ul, ol, li, dl, dt, dd, em, strong, dfn, code, q, samp, kbd, var, cite, abbr, acronym, sub, sup, br, pre

A django site