src/pyams_i18n/expr.py
changeset 7 0e4957081cd1
child 9 017ad36cc2ba
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_i18n/expr.py	Sat Mar 28 23:25:23 2015 +0100
@@ -0,0 +1,54 @@
+#
+# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+
+# import interfaces
+from pyams_i18n.interfaces import INegotiator
+
+# import packages
+from chameleon.astutil import Symbol
+from chameleon.tales import StringExpr
+from pyams_utils.registry import query_utility
+from pyams_utils.tales import ContextExprMixin
+
+
+def render_i18n_expression(econtext, name):
+    """Render an I18n expression"""
+
+    name = name.strip()
+    if '.' in name:
+        context_name, attr = name.split('.')
+    else:
+        context_name = 'context',
+        attr = name
+    context = econtext.get(context_name)
+    result = getattr(context, attr)
+    if not isinstance(result, dict):
+        return result
+    request = econtext.get('request')
+    lang = request.locale_name
+    value = result.get(lang)
+    if not value:
+        negotiator = query_utility(INegotiator)
+        if (negotiator is not None) and (negotiator.server_language != lang):
+            return result.get(negotiator.server_language)
+    return value
+
+
+class I18nExpr(ContextExprMixin, StringExpr):
+    """i18n:context.attribute TALES expression"""
+
+    transform = Symbol(render_i18n_expression)