In Django's template engine, is it possible to run a filter through an entire array?
For example, if I have an array of开发者_开发百科 datetime.date
objects, I would like to apply a date format filter to each of its elements, while still making use of the default string representation of the array.
Given a date array that looks like:
[datetime.date(2011, 2, 28), datetime.date(2011, 3, 1), datetime.date(2011, 3, 2)]
Assuming that I already passed it to the template's context, I'd like to do this in the template:
<script>
// ...
var dates = {{ my_date_array|date:'b d, Y' }};
// ...
</script>
so it produces:
var dates = ['Feb 28, 2011', 'Mar 1, 2011', 'Mar 2, 2011'];
..instead of having to loop through the elements of the array.
Is this possible by default, without creating a custom filter?
Looking at the source, I'd say that's not possible using the default date
filter.
You will have to either use a loop in your template, or create a custom filter that accepts a list of date objects.
Update:
It should be relatively easy to create your own filter by making use of the existing one. For example:
from django.template.defaultfilters import date
from django import template
register = template.Library()
# Only mildly tested. Use with caution.
def datelist(values, arg=None):
try:
outstr = "', '".join([date(v, arg) for v in values])
except TypeError: # non-iterable?
outstr = date(values, arg)
return "['%s']" % outstr
register.filter('datelist', datelist)
If you don't like that approach for determining iterable objects, you could also use:
# requires Python >=2.4
from collections import Iterable
if isinstance(values, Iterable):
# ....
精彩评论