Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #5567 -- Added a "last" filter. Based on a patch from darkpixel.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@6998 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit a7da12d32090e887b72093b7e8f2870a8d7cf3a7 1 parent 1f6bc7f
Malcolm Tredinnick authored January 06, 2008
9  django/template/defaultfilters.py
@@ -449,6 +449,14 @@ def join(value, arg):
449 449
         return data
450 450
 join.is_safe = True
451 451
 
  452
+def last(value):
  453
+    "Returns the last item in a list"
  454
+    try:
  455
+        return value[-1]
  456
+    except IndexError:
  457
+        return u''
  458
+last.is_safe = True
  459
+
452 460
 def length(value):
453 461
     """Returns the length of the value - useful for lists."""
454 462
     return len(value)
@@ -800,6 +808,7 @@ def pprint(value):
800 808
 register.filter(get_digit)
801 809
 register.filter(iriencode)
802 810
 register.filter(join)
  811
+register.filter(last)
803 812
 register.filter(length)
804 813
 register.filter(length_is)
805 814
 register.filter(linebreaks)
5  docs/templates.txt
@@ -1403,6 +1403,11 @@ join
1403 1403
 
1404 1404
 Joins a list with a string, like Python's ``str.join(list)``.
1405 1405
 
  1406
+last
  1407
+~~~~
  1408
+
  1409
+Returns the last item in a list.
  1410
+
1406 1411
 length
1407 1412
 ~~~~~~
1408 1413
 
3  tests/regressiontests/templates/filters.py
@@ -179,6 +179,9 @@ def get_filter_tests():
179 179
         'filter-first01': ('{{ a|first }} {{ b|first }}', {"a": ["a&b", "x"], "b": [mark_safe("a&b"), "x"]}, "a&b a&b"),
180 180
         'filter-first02': ('{% autoescape off %}{{ a|first }} {{ b|first }}{% endautoescape %}', {"a": ["a&b", "x"], "b": [mark_safe("a&b"), "x"]}, "a&b a&b"),
181 181
 
  182
+        'filter-last01': ('{{ a|last }} {{ b|last }}', {"a": ["x", "a&b"], "b": ["x", mark_safe("a&b")]}, "a&b a&b"),
  183
+        'filter-last02': ('{% autoescape off %}{{ a|last }} {{ b|last }}{% endautoescape %}', {"a": ["x", "a&b"], "b": ["x", mark_safe("a&b")]}, "a&b a&b"),
  184
+
182 185
         'filter-random01': ('{{ a|random }} {{ b|random }}', {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"), mark_safe("a&b")]}, "a&b a&b"),
183 186
         'filter-random02': ('{% autoescape off %}{{ a|random }} {{ b|random }}{% endautoescape %}', {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"), mark_safe("a&b")]}, "a&b a&b"),
184 187
 

0 notes on commit a7da12d

Please sign in to comment.
Something went wrong with that request. Please try again.