Skip to content

Commit

Permalink
Allow to reconfigure the default for truncate leeway
Browse files Browse the repository at this point in the history
Refs #610
  • Loading branch information
mitsuhiko committed Jan 10, 2017
1 parent e73c574 commit fb47dfa
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGES
Expand Up @@ -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
-------------
Expand Down
6 changes: 6 additions & 0 deletions docs/api.rst
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions jinja2/defaults.py
Expand Up @@ -44,6 +44,7 @@
'compiler.ascii_str': True,
'urlize.rel': 'noopener',
'urlize.target': None,
'truncate.leeway': 5,
'json.dumps_function': None,
'json.dumps_kwargs': {'sort_keys': True},
}
Expand Down
7 changes: 6 additions & 1 deletion jinja2/filters.py
Expand Up @@ -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
Expand All @@ -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:
Expand Down

0 comments on commit fb47dfa

Please sign in to comment.