Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Issue #121: The truncate filter now counts the length

of the *end* parameter when truncating a string.

This is the same behavior as Django's truncate filter:

https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#truncatechars
  • Loading branch information...
commit 3c75c961b4fbdf8a6bede3aa5ef80efdbcb9c80a 1 parent 63227f0
@berkerpeksag berkerpeksag authored
Showing with 14 additions and 7 deletions.
  1. +7 −6 jinja2/filters.py
  2. +7 −1 jinja2/testsuite/filters.py
View
13 jinja2/filters.py
@@ -456,21 +456,22 @@ def do_truncate(s, length=255, killwords=False, end='...'):
.. sourcecode:: jinja
- {{ "foo bar"|truncate(5) }}
+ {{ "foo bar baz"|truncate(9) }}
+ -> "foo ba..."
+ {{ "foo bar baz"|truncate(9, True) }}
-> "foo ..."
- {{ "foo bar"|truncate(5, True) }}
- -> "foo b..."
+
"""
- if len(s) <= length:
+ if len(s) <= (length + len(end)):
return s
elif killwords:
- return s[:length] + end
+ return s[:length - len(end)] + end
words = s.split(' ')
result = []
m = 0
for word in words:
m += len(word) + 1
- if m > length:
+ if m > (length - len(end)):
break
result.append(word)
result.append(end)
View
8 jinja2/testsuite/filters.py
@@ -227,7 +227,13 @@ def test_truncate(self):
)
out = tmpl.render(data='foobar baz bar' * 1000,
smalldata='foobar baz bar')
- assert out == 'foobar baz barf>>>|foobar baz >>>|foobar baz bar'
+ msg = 'Current output: %s' % out
+ assert out == 'foobar baz b>>>|foobar baz >>>|foobar baz bar', msg
+
+ def test_truncate_end_length(self):
+ tmpl = env.from_string('{{ "Joel is a slug"|truncate(9, true) }}')
+ out = tmpl.render()
+ assert out == 'Joel i...', 'Current output: %s' % out
def test_upper(self):
tmpl = env.from_string('{{ "foo"|upper }}')
Please sign in to comment.
Something went wrong with that request. Please try again.