publik: add removeprefix and removesuffix filters (#74786)
gitea/publik-django-templatetags/pipeline/head This commit looks good Details

This commit is contained in:
Lauréline Guérin 2023-04-21 10:38:51 +02:00
parent c1e3cba42f
commit bdc8a59ff0
No known key found for this signature in database
GPG Key ID: 1FAB9B9B4F93D473
2 changed files with 50 additions and 2 deletions

View File

@ -22,7 +22,7 @@ from decimal import InvalidOperation as DecimalInvalidOperation
from django import template
from django.template import defaultfilters
from django.utils.encoding import force_text
from django.utils.encoding import force_str
from publik_django_templatetags.publik import utils
@ -62,7 +62,25 @@ def as_list(obj):
@register.filter
def split(string, separator=' '):
return (force_text(string) or '').split(separator)
return (force_str(string) or '').split(separator)
@register.filter
def removeprefix(string, prefix=None):
if not string:
return ''
value = force_str(string)
prefix = force_str(prefix)
return value.removeprefix(prefix)
@register.filter
def removesuffix(string, suffix=None):
if not string:
return ''
value = force_str(string)
suffix = force_str(suffix)
return value.removesuffix(suffix)
@register.filter

View File

@ -63,6 +63,36 @@ def test_split():
assert t.render(Context({'plop': 42})) == '42 '
def test_removeprefix():
t = Template('{{ foo|removeprefix }}')
assert t.render(Context({})) == ''
assert t.render(Context({'foo': None})) == ''
assert t.render(Context({'foo': 'foo bar'})) == 'foo bar'
t = Template('{{ foo|removeprefix:"" }}')
assert t.render(Context({'foo': 'foo bar'})) == 'foo bar'
t = Template('{{ foo|removeprefix:"XY" }}')
assert t.render(Context({'foo': 'XYfoo barXY'})) == 'foo barXY'
assert t.render(Context({'foo': 'foo bar'})) == 'foo bar'
assert t.render(Context({'foo': 'xyfoo barXY'})) == 'xyfoo barXY'
assert t.render(Context({'foo': ' XYfoo barXY'})) == ' XYfoo barXY'
assert t.render(Context({'foo': 'XYXYfoo barXY'})) == 'XYfoo barXY'
def test_removesuffix():
t = Template('{{ foo|removesuffix }}')
assert t.render(Context()) == ''
assert t.render(Context({'foo': None})) == ''
assert t.render(Context({'foo': 'foo bar'})) == 'foo bar'
t = Template('{{ foo|removesuffix:"" }}')
assert t.render(Context({'foo': 'foo bar'})) == 'foo bar'
t = Template('{{ foo|removesuffix:"XY" }}')
assert t.render(Context({'foo': 'XYfoo barXY'})) == 'XYfoo bar'
assert t.render(Context({'foo': 'foo bar'})) == 'foo bar'
assert t.render(Context({'foo': 'XYfoo barxy'})) == 'XYfoo barxy'
assert t.render(Context({'foo': 'XYfoo barXY '})) == 'XYfoo barXY '
assert t.render(Context({'foo': 'XYfoo barXYXY'})) == 'XYfoo barXY'
def test_first():
t = Template('{{ foo|first }}')