Login

Snippets by davidchambers

Snippet List

Template tag to create a list from one or more variables and/or literals

This code is taken from a [Stack Overflow answer by Will Hardy](http://stackoverflow.com/questions/3715550/creating-a-list-on-the-fly-in-a-django-template/3715794#3715794). Usage: `{% collect var1 var2 'foo' 'bar' 5 as some_list %}`. Sometimes one wishes to create a list on the fly within a template. Perhaps a collection needs to be passed to a template filter, but the collection cannot be created in the view since the values of one or more of its items are set in the template. A contrived example: {% with 5 as max %}{% with posts|length as len %} {% for post in posts %} {% if forloop.counter <= max %} {% include 'excerpt.dhtml' %} {% endif %} {% endfor %} {% collect len max as limits %} <p>Displaying {{ limits|minimum }} of {{ len }} post{{ posts|pluralize }}.</p> {% endwith %}{% endwith %} The final line will state how many posts are displayed: something like "5 of 24" or "2 of 2". This particular problem can be solved in a number of other ways, some of which are more appropriate. Having a template tag that can create lists on the fly is potentially useful in quite a few situations, though. I don't know whether this need is common enough to warrant being in the core. If something like this is to be included one day, it'd be much nicer to overload the `with` tag than to introduce a new tag. `{% with var1 var2 var3 as some_list %}` reads well.

  • template-tags
Read More

davidchambers has posted 1 snippet.