Added "truncate" TALES extension
authorThierry Florac <tflorac@ulthar.net>
Wed, 14 Nov 2018 17:56:13 +0100
changeset 280 f37f19b7fff3
parent 279 1506cc3bc32e (current diff)
parent 278 5ef130497172 (diff)
child 281 b04690a8d80f
Added "truncate" TALES extension
src/pyams_utils/text.py
--- a/src/pyams_utils/text.py	Wed Nov 14 17:52:55 2018 +0100
+++ b/src/pyams_utils/text.py	Wed Nov 14 17:56:13 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
@@ -55,6 +55,22 @@
     return text
 
 
+@adapter_config(name='truncate', context=(Interface, Interface, Interface), provides=ITALESExtension)
+class TruncateCharsTalesExtension(ContextRequestViewAdapter):
+    """extension:truncate(value, length, max) TALES expression
+
+    Truncates a sentence if it is longer than the specified 'length' characters.
+    Truncated strings will end with an 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)
+
+
 @adapter_config(name='raw', context=(str, IRequest), provides=IHTMLRenderer)
 class BaseHTMLRenderer(ContextRequestAdapter):
     """Raw text HTML renderer