Added I18n TALES extension
authorThierry Florac <thierry.florac@onf.fr>
Mon, 17 Sep 2018 17:36:44 +0200
changeset 73 d507481e1c13
parent 72 4146dbce4034
child 74 d274d856e6df
Added I18n TALES extension
src/pyams_i18n/expr.py
--- a/src/pyams_i18n/expr.py	Thu Jun 28 08:39:51 2018 +0200
+++ b/src/pyams_i18n/expr.py	Mon Sep 17 17:36:44 2018 +0200
@@ -15,12 +15,15 @@
 
 # import standard library
 
-# import interfaces
-from pyams_i18n.interfaces import II18n
-
 # import packages
 from chameleon.astutil import Symbol
 from chameleon.tales import StringExpr
+from zope.interface import Interface
+
+# import interfaces
+from pyams_i18n.interfaces import II18n
+from pyams_utils.adapter import adapter_config, ContextRequestViewAdapter
+from pyams_utils.interfaces.tales import ITALESExtension
 from pyams_utils.tales import ContextExprMixin
 
 
@@ -50,3 +53,18 @@
     """i18n:context.attribute TALES expression"""
 
     transform = Symbol(render_i18n_expression)
+
+
+@adapter_config(name='i18n', context=(Interface, Interface, Interface), provides=ITALESExtension)
+class I18NTalesExtension(ContextRequestViewAdapter):
+    """extension:i18n(context, attribute, default=None) TALES extension
+
+    Similar to standard i18n: TALES expression, but provides a default value.
+    """
+
+    def render(self, context, attribute, default=None):
+        try:
+            value = II18n(context).query_attribute(attribute, request=self.request)
+        except AttributeError:
+            value = default
+        return value