Created new tales Extention to ellipsis to long sentence dev-dc
authorDamien Correia
Wed, 14 Nov 2018 15:52:57 +0100
branchdev-dc
changeset 278 5ef130497172
parent 251 b9398ca282c7
child 280 f37f19b7fff3
Created new tales Extention to ellipsis to long sentence
src/pyams_utils/text.py
--- a/src/pyams_utils/text.py	Fri Nov 09 11:55:14 2018 +0100
+++ b/src/pyams_utils/text.py	Wed Nov 14 15:52:57 2018 +0100
@@ -28,9 +28,9 @@
 
 def get_text_start(text, length, max=0):
     """Get first words of given text with maximum given length
-    
+
     If *max* is specified, text is shortened only if remaining text is longer this value
-    
+
     :param str text: initial text
     :param integer length: maximum length of resulting text
     :param integer max: if > 0, *text* is shortened only if remaining text is longer than max
@@ -185,3 +185,18 @@
         if end_tag:
             elements[-1] = '<{0}>{1}</{0}>'.format(end_tag, elements[-1])
         return br.join(elements)
+
+@adapter_config(name='truncatechars', context=(Interface, Interface, Interface), provides=ITALESExtension)
+class TruncateCharsTalesExtension(ContextRequestViewAdapter):
+    """extension:truncatechars(value, length, max) TALES expression
+
+    Truncates a sentence if it is longer than the specified 'length' of characters.
+    Truncated strings will end with a ellipsis character (“…”)
+    see also 'get_text_start'
+    """
+
+    @staticmethod
+    def render(value, length=50, max=0):
+        if not value:
+            return ''
+        return get_text_start(value, length, max=max)