templatetags: add removeprefix and removesuffix filters (#45780)

This commit is contained in:
Nicolas Roche 2020-08-07 17:00:06 +02:00
parent 40e32ff67d
commit 017b20e7f8
2 changed files with 51 additions and 0 deletions

View File

@ -298,6 +298,29 @@ def strip(string, chars=None):
else:
return force_text(string).strip()
@register.filter
def removeprefix(string, prefix):
if not string:
return ''
value = force_text(string)
prefix = force_text(prefix)
if prefix and value.startswith(prefix):
return value[len(prefix):]
return value
@register.filter
def removesuffix(string, suffix):
if not string:
return ''
value = force_text(string)
suffix = force_text(suffix)
if suffix and value.endswith(suffix):
return value[:-len(suffix)]
return value
@register.filter(name='get_group')
def get_group(group_list, group_name):
ret = []

View File

@ -8,6 +8,7 @@ import pytest
from django.core.files import File
from django.core.files.storage import default_storage
from django.template import Context, Template
from django.template.exceptions import TemplateSyntaxError
from django.test import override_settings
from django.test.client import RequestFactory
from django.contrib.auth.models import User, Group, AnonymousUser
@ -141,6 +142,33 @@ def test_strip_templatetag():
assert tmpl.render(Context({'foo': 'XXfoo barXYX'})) == 'foo bar'
assert tmpl.render(Context({'foo': ' foo barXX'})) == ' foo bar'
def test_removeprefix_templatetag():
with pytest.raises(TemplateSyntaxError, match='removeprefix requires 2 arguments, 1 provided'):
tmpl = Template('{{ foo|removeprefix }}')
tmpl = Template('{{ foo|removeprefix:"" }}')
assert tmpl.render(Context({'foo': 'foo bar'})) == 'foo bar'
tmpl = Template('{{ foo|removeprefix:"XY" }}')
assert tmpl.render(Context({'foo': 'XYfoo barXY'})) == 'foo barXY'
assert tmpl.render(Context({'foo': 'foo bar'})) == 'foo bar'
assert tmpl.render(Context({'foo': 'xyfoo barXY'})) == 'xyfoo barXY'
assert tmpl.render(Context({'foo': ' XYfoo barXY'})) == ' XYfoo barXY'
assert tmpl.render(Context({'foo': 'XYXYfoo barXY'})) == 'XYfoo barXY'
def test_removesuffix_templatetag():
with pytest.raises(TemplateSyntaxError, match='removesuffix requires 2 arguments, 1 provided'):
tmpl = Template('{{ foo|removesuffix }}')
tmpl = Template('{{ foo|removesuffix:"" }}')
assert tmpl.render(Context({'foo': 'foo bar'})) == 'foo bar'
tmpl = Template('{{ foo|removesuffix:"XY" }}')
assert tmpl.render(Context({'foo': 'XYfoo barXY'})) == 'XYfoo bar'
assert tmpl.render(Context({'foo': 'foo bar'})) == 'foo bar'
assert tmpl.render(Context({'foo': 'XYfoo barxy'})) == 'XYfoo barxy'
assert tmpl.render(Context({'foo': 'XYfoo barXY '})) == 'XYfoo barXY '
assert tmpl.render(Context({'foo': 'XYfoo barXYXY'})) == 'XYfoo barXY'
def test_get_group():
context = Context({'cities': [
{'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},