From 9a5d522cb577cc455a1b022acd60a90e08ebfa1a Mon Sep 17 00:00:00 2001 From: Matteo Ferrando Date: Wed, 21 Mar 2018 12:47:46 -0400 Subject: [PATCH] add chars option to trim --- CHANGES.rst | 2 ++ jinja2/filters.py | 6 +++--- tests/test_filters.py | 8 ++++++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 692a5161..fe99937d 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -22,6 +22,8 @@ Unreleased - Int and float literals can be written with the '_' separator for legibility, like 12_345. :pr:`923` - Fix a bug causing deadlocks in ``LRUCache.setdefault``. :pr:`1000` +- The ``trim`` filter takes an optional string of characters to trim. + :pr:`828` Version 2.10.2 diff --git a/jinja2/filters.py b/jinja2/filters.py index 488aab56..40dbfcb3 100644 --- a/jinja2/filters.py +++ b/jinja2/filters.py @@ -757,9 +757,9 @@ def do_format(value, *args, **kwargs): return soft_unicode(value) % (kwargs or args) -def do_trim(value): - """Strip leading and trailing whitespace.""" - return soft_unicode(value).strip() +def do_trim(value, chars=None): + """Strip leading and trailing characters, by default whitespace.""" + return soft_unicode(value).strip(chars) def do_striptags(value): diff --git a/tests/test_filters.py b/tests/test_filters.py index cfa1f43d..33123f97 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -85,6 +85,14 @@ class TestFilter(object): out = tmpl.render() assert out == '<">&' + @pytest.mark.parametrize( + ("chars", "expect"), [(None, "..stays.."), (".", " ..stays"), (" .", "stays")] + ) + def test_trim(self, env, chars, expect): + tmpl = env.from_string("{{ foo|trim(chars) }}") + out = tmpl.render(foo=" ..stays..", chars=chars) + assert out == expect + def test_striptags(self, env): tmpl = env.from_string('''{{ foo|striptags }}''') out = tmpl.render(foo='

just a small \n ' -- 2.47.2