diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index 2f46dc7b57..ff8d4184ea 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -422,11 +422,19 @@ def safe(value): """ Marks the value as a string that should not be auto-escaped. """ - from django.utils.safestring import mark_safe return mark_safe(value) safe.is_safe = True safe = stringfilter(safe) +def safeseq(value): + """ + A "safe" filter for sequences. Marks each element in the sequence, + individually, as safe, after converting them to unicode. Returns a list + with the results. + """ + return [mark_safe(force_unicode(obj)) for obj in value] +safeseq.is_safe = True + def removetags(value, tags): """Removes a space separated list of [X]HTML tags from the output.""" tags = [re.escape(tag) for tag in tags.split()] @@ -876,6 +884,7 @@ register.filter(removetags) register.filter(random) register.filter(rjust) register.filter(safe) +register.filter(safeseq) register.filter('slice', slice_) register.filter(slugify) register.filter(stringformat) diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt index a79063c9de..17e6e8bf9e 100644 --- a/docs/ref/templates/builtins.txt +++ b/docs/ref/templates/builtins.txt @@ -1330,6 +1330,21 @@ safe Marks a string as not requiring further HTML escaping prior to output. When autoescaping is off, this filter has no effect. +.. templatefilter:: safeseq + +safeseq +~~~~~~~ + +Applies the :tfilter:`safe` filter to each element of a sequence. Useful in +conjunction with other filters that operate on sequences, such as +:tfilter:`join`. For example:: + + {{ some_list|safeseq|join:", " }} + +You couldn't use the :tfilter:`safe` filter directly in this case, as it would +first convert the variable into a string, rather than working with the +individual elements of the sequence. + .. templatefilter:: slice slice diff --git a/tests/regressiontests/templates/filters.py b/tests/regressiontests/templates/filters.py index 5bc6430834..116ffbf131 100644 --- a/tests/regressiontests/templates/filters.py +++ b/tests/regressiontests/templates/filters.py @@ -199,6 +199,9 @@ def get_filter_tests(): 'filter-safe01': ("{{ a }} -- {{ a|safe }}", {"a": u"hello"}, "<b>hello</b> -- hello"), 'filter-safe02': ("{% autoescape off %}{{ a }} -- {{ a|safe }}{% endautoescape %}", {"a": "hello"}, u"hello -- hello"), + 'filter-safeseq01': ('{{ a|join:", " }} -- {{ a|safeseq|join:", " }}', {"a": ["&", "<"]}, "&, < -- &, <"), + 'filter-safeseq02': ('{% autoescape off %}{{ a|join:", " }} -- {{ a|safeseq|join:", " }}{% endautoescape %}', {"a": ["&", "<"]}, "&, < -- &, <"), + 'filter-removetags01': ('{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}', {"a": "x

y

", "b": mark_safe("x

y

")}, u"x <p>y</p> x

y

"), 'filter-removetags02': ('{% autoescape off %}{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}{% endautoescape %}', {"a": "x

y

", "b": mark_safe("x

y

")}, u"x

y

x

y

"),