From: Armin Ronacher Date: Tue, 10 Jan 2017 08:21:14 +0000 (+0100) Subject: Allow to reconfigure the default for truncate leeway X-Git-Tag: 2.9.4~2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=fb47dfac606f8067b77db1e805ad2cbd5cd6cd7f;p=thirdparty%2Fjinja.git Allow to reconfigure the default for truncate leeway Refs #610 --- diff --git a/CHANGES b/CHANGES index d2803654..f872f350 100644 --- a/CHANGES +++ b/CHANGES @@ -12,6 +12,8 @@ Version 2.9.4 - Resolved an issue where top-level output silencing after known extend blocks could generate invalid code when blocks where contained in if statements. (#651) +- Made the `truncate.leeway` default configurable to improve compatibility + with older templates. Version 2.9.3 ------------- diff --git a/docs/api.rst b/docs/api.rst index de4d2e44..443d0535 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -584,6 +584,12 @@ Example:: If this is set to False then all strings are stored as unicode internally. +``truncate.leeway``: + Configures the leeway default for the `truncate` filter. Leeway as + introduced in 2.9 but to restore compatibility with older templates + it can be configured to `0` to get the old behavior back. The default + is `5`. + ``urlize.rel``: A string that defines the items for the `rel` attribute of generated links with the `urlize` filter. These items are always added. The diff --git a/jinja2/defaults.py b/jinja2/defaults.py index e29ce565..35903883 100644 --- a/jinja2/defaults.py +++ b/jinja2/defaults.py @@ -44,6 +44,7 @@ DEFAULT_POLICIES = { 'compiler.ascii_str': True, 'urlize.rel': 'noopener', 'urlize.target': None, + 'truncate.leeway': 5, 'json.dumps_function': None, 'json.dumps_kwargs': {'sort_keys': True}, } diff --git a/jinja2/filters.py b/jinja2/filters.py index e13bc623..f4cd7968 100644 --- a/jinja2/filters.py +++ b/jinja2/filters.py @@ -463,7 +463,8 @@ def do_indent(s, width=4, indentfirst=False): return rv -def do_truncate(s, length=255, killwords=False, end='...', leeway=5): +@environmentfilter +def do_truncate(env, s, length=255, killwords=False, end='...', leeway=None): """Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise @@ -484,7 +485,11 @@ def do_truncate(s, length=255, killwords=False, end='...', leeway=5): {{ "foo bar baz qux"|truncate(11, False, '...', 0) }} -> "foo bar..." + The default leeway on newer Jinja2 versions is 5 and was 0 before but + can be reconfigured globally. """ + if leeway is None: + leeway = env.policies['truncate.leeway'] assert length >= len(end), 'expected length >= %s, got %s' % (len(end), length) assert leeway >= 0, 'expected leeway >= 0, got %s' % leeway if len(s) <= length + leeway: