diff options
author | Lars Kollstedt <lk@man-da.de> | 2020-03-10 12:26:44 +0100 |
---|---|---|
committer | David Lord <davidism@gmail.com> | 2021-04-05 09:50:45 -0700 |
commit | 8016b5f139473675ace9a5a1eb845298335e9dd2 (patch) | |
tree | e6647b3929df3a376aec6546fb15cee486742205 | |
parent | 7bea9193f48b6f8fac147ace7ca349a05e594af4 (diff) | |
download | jinja2-8016b5f139473675ace9a5a1eb845298335e9dd2.tar.gz |
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.
-rw-r--r-- | CHANGES.rst | 2 | ||||
-rw-r--r-- | src/jinja2/filters.py | 15 | ||||
-rw-r--r-- | tests/test_filters.py | 4 |
3 files changed, 18 insertions, 3 deletions
diff --git a/CHANGES.rst b/CHANGES.rst index 73cbd2d..1e0ec0e 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 356248a..5ff0bdd 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 5a11d3f..2c119c3 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"), ( |