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
.. 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)
)
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 }}')