From a7da12d32090e887b72093b7e8f2870a8d7cf3a7 Mon Sep 17 00:00:00 2001 From: Malcolm Tredinnick Date: Sun, 6 Jan 2008 03:53:33 +0000 Subject: [PATCH] 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 --- django/template/defaultfilters.py | 9 +++++++++ docs/templates.txt | 5 +++++ tests/regressiontests/templates/filters.py | 3 +++ 3 files changed, 17 insertions(+) diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index 7ef531e688e..ddd48146f28 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -449,6 +449,14 @@ def join(value, arg): return data join.is_safe = True +def last(value): + "Returns the last item in a list" + try: + return value[-1] + except IndexError: + return u'' +last.is_safe = True + def length(value): """Returns the length of the value - useful for lists.""" return len(value) @@ -800,6 +808,7 @@ register.filter(force_escape) register.filter(get_digit) register.filter(iriencode) register.filter(join) +register.filter(last) register.filter(length) register.filter(length_is) register.filter(linebreaks) diff --git a/docs/templates.txt b/docs/templates.txt index ffda3215123..c3ed7e5a1c1 100644 --- a/docs/templates.txt +++ b/docs/templates.txt @@ -1403,6 +1403,11 @@ join Joins a list with a string, like Python's ``str.join(list)``. +last +~~~~ + +Returns the last item in a list. + length ~~~~~~ diff --git a/tests/regressiontests/templates/filters.py b/tests/regressiontests/templates/filters.py index f38b2cdef1e..fd73dc57baa 100644 --- a/tests/regressiontests/templates/filters.py +++ b/tests/regressiontests/templates/filters.py @@ -179,6 +179,9 @@ def get_filter_tests(): 'filter-first01': ('{{ a|first }} {{ b|first }}', {"a": ["a&b", "x"], "b": [mark_safe("a&b"), "x"]}, "a&b a&b"), 'filter-first02': ('{% autoescape off %}{{ a|first }} {{ b|first }}{% endautoescape %}', {"a": ["a&b", "x"], "b": [mark_safe("a&b"), "x"]}, "a&b a&b"), + 'filter-last01': ('{{ a|last }} {{ b|last }}', {"a": ["x", "a&b"], "b": ["x", mark_safe("a&b")]}, "a&b a&b"), + 'filter-last02': ('{% autoescape off %}{{ a|last }} {{ b|last }}{% endautoescape %}', {"a": ["x", "a&b"], "b": ["x", mark_safe("a&b")]}, "a&b a&b"), + 'filter-random01': ('{{ a|random }} {{ b|random }}', {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"), mark_safe("a&b")]}, "a&b a&b"), '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"),