From: Lars Kollstedt Date: Tue, 10 Mar 2020 11:26:44 +0000 (+0100) Subject: filters.py: do_indent: ident filter can indent with arbitrary characters X-Git-Tag: 3.0.0rc1~21^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=8016b5f139473675ace9a5a1eb845298335e9dd2;p=thirdparty%2Fjinja.git filters.py: do_indent: ident filter can indent with arbitrary characters Allow indention with generic characters, e.g. Tabs. Implemenented the behavior requested in https://github.com/pallets/jinja/pull/1167#issuecomment-612644701 The width param can be string or int, if it is string it's the raw indention e.g. "\t". If it's int it's the number of spaces. In other cases an FilterArgumentError is raised, to avoid confusion. --- diff --git a/CHANGES.rst b/CHANGES.rst index 73cbd2df..1e0ec0ee 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -48,6 +48,8 @@ Unreleased or ``@contextfunction``. :issue:`842`, :pr:`1248` - Support ``pgettext`` and ``npgettext`` (message contexts) in i18n extension. :issue:`441` +- The ``|indent`` filter's ``width`` argument can be a string to + indent by. :pr:`1167` Version 2.11.3 diff --git a/src/jinja2/filters.py b/src/jinja2/filters.py index 356248a3..5ff0bdde 100644 --- a/src/jinja2/filters.py +++ b/src/jinja2/filters.py @@ -748,20 +748,29 @@ def do_urlize( return rv -def do_indent(s: str, width: int = 4, first: bool = False, blank: bool = False) -> str: +def do_indent( + s: str, width: t.Union[int, str] = 4, first: bool = False, blank: bool = False +) -> str: """Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. - :param width: Number of spaces to indent by. + :param width: Number of spaces, or a string, to indent by. :param first: Don't skip indenting the first line. :param blank: Don't skip indenting empty lines. + .. versionchanged:: 3.0 + ``width`` can be a string. + .. versionchanged:: 2.10 Blank lines are not indented by default. Rename the ``indentfirst`` argument to ``first``. """ - indention = " " * width + if isinstance(width, str): + indention = width + else: + indention = " " * width + newline = "\n" if isinstance(s, Markup): diff --git a/tests/test_filters.py b/tests/test_filters.py index 5a11d3f9..2c119c37 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -185,6 +185,10 @@ class TestFilter: """ self._test_indent_multiline_template(env, markup=True) + def test_indent_width_string(self, env): + t = env.from_string("{{ 'jinja\nflask'|indent(width='>>> ', first=True) }}") + assert t.render() == ">>> jinja\n>>> flask" + @pytest.mark.parametrize( ("value", "expect"), (