]> git.ipfire.org Git - thirdparty/jinja.git/commitdiff
filters.py: do_indent: ident filter can indent with arbitrary characters 1167/head
authorLars Kollstedt <lk@man-da.de>
Tue, 10 Mar 2020 11:26:44 +0000 (12:26 +0100)
committerDavid Lord <davidism@gmail.com>
Mon, 5 Apr 2021 16:50:45 +0000 (09:50 -0700)
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.

CHANGES.rst
src/jinja2/filters.py
tests/test_filters.py

index 73cbd2df49bfdd88f665b35f561d093bbcab1270..1e0ec0ee9c020232bb22ba5c15c6f0f1bfc99901 100644 (file)
@@ -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
index 356248a35f9907aa3e071c585142255e6e4bc9a3..5ff0bdde51add80c9bd274a77d76dee8650d1fd4 100644 (file)
@@ -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):
index 5a11d3f9c6be54e1098d779cbafb93cbf2827c17..2c119c37efc81b9afb92f7d878917012ff975cf2 100644 (file)
@@ -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"),
         (