]> git.ipfire.org Git - thirdparty/jinja.git/commitdiff
Issue #121: The truncate filter now counts the length 267/head
authorBerker Peksag <berker.peksag@gmail.com>
Sun, 8 Sep 2013 15:09:29 +0000 (18:09 +0300)
committerBerker Peksag <berker.peksag@gmail.com>
Fri, 13 Sep 2013 22:09:52 +0000 (01:09 +0300)
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

jinja2/filters.py
jinja2/testsuite/filters.py

index 70bb94824faa26d0879e1ccbd1d8183ff2f81f31..2b6ef08a75709d430452512f7693ff6d245a4fa9 100644 (file)
@@ -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)
index 9d5c95228c96a0e6904ffdb738bc3ac59fa7c0ec..4958202124e226bcacbb4222068e2678e5673503 100644 (file)
@@ -227,7 +227,13 @@ class FilterTestCase(JinjaTestCase):
         )
         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 }}')