Fixed #9701 -- Added a "safeseq" template filter.

This is like "safe", except it operates on the individual elements of a
sequence, rather than treating the whole argument as a string.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@9952 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Malcolm Tredinnick 2009-03-02 08:16:33 +00:00
parent 851461aa72
commit dfddf129f0
3 changed files with 28 additions and 1 deletions

View File

@ -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)

View File

@ -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

View File

@ -199,6 +199,9 @@ def get_filter_tests():
'filter-safe01': ("{{ a }} -- {{ a|safe }}", {"a": u"<b>hello</b>"}, "&lt;b&gt;hello&lt;/b&gt; -- <b>hello</b>"),
'filter-safe02': ("{% autoescape off %}{{ a }} -- {{ a|safe }}{% endautoescape %}", {"a": "<b>hello</b>"}, u"<b>hello</b> -- <b>hello</b>"),
'filter-safeseq01': ('{{ a|join:", " }} -- {{ a|safeseq|join:", " }}', {"a": ["&", "<"]}, "&amp;, &lt; -- &, <"),
'filter-safeseq02': ('{% autoescape off %}{{ a|join:", " }} -- {{ a|safeseq|join:", " }}{% endautoescape %}', {"a": ["&", "<"]}, "&, < -- &, <"),
'filter-removetags01': ('{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}', {"a": "<a>x</a> <p><b>y</b></p>", "b": mark_safe("<a>x</a> <p><b>y</b></p>")}, u"x &lt;p&gt;y&lt;/p&gt; x <p>y</p>"),
'filter-removetags02': ('{% autoescape off %}{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}{% endautoescape %}', {"a": "<a>x</a> <p><b>y</b></p>", "b": mark_safe("<a>x</a> <p><b>y</b></p>")}, u"x <p>y</p> x <p>y</p>"),