templatetags: add strip filters (#41701)

This commit is contained in:
Nicolas Roche 2020-04-20 16:43:24 +02:00 committed by Thomas NOEL
parent e60da7345a
commit 75875bfd5e
2 changed files with 20 additions and 0 deletions

View File

@ -286,6 +286,15 @@ def get(obj, key):
def split(string, separator=' '):
return (string or '').split(separator)
@register.filter
def strip(string, chars=None):
if not string:
return ''
if chars:
return force_text(string).strip(force_text(chars))
else:
return force_text(string).strip()
@register.filter(name='get_group')
def get_group(group_list, group_name):
ret = []

View File

@ -129,6 +129,17 @@ def test_split():
t = Template('{% for x in plop|split:"|" %}{{x}} {% endfor %}')
assert t.render(Context({'plop': 'ab|cd|ef'})) == 'ab cd ef '
def test_strip_templatetag():
tmpl = Template('{{ foo|strip }}')
assert tmpl.render(Context()) == ''
assert tmpl.render(Context({'foo': None})) == ''
assert tmpl.render(Context({'foo': ' foo bar '})) == 'foo bar'
assert tmpl.render(Context({'foo': ' foo bar\t'})) == 'foo bar'
assert tmpl.render(Context({'foo': ' félé '})) == 'félé'
tmpl = Template('{{ foo|strip:"XY" }}')
assert tmpl.render(Context({'foo': 'XXfoo barXYX'})) == 'foo bar'
assert tmpl.render(Context({'foo': ' foo barXX'})) == ' foo bar'
def test_get_group():
context = Context({'cities': [
{'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},