diff libervia/server/pages.py @ 1169:97e850e6fae9

pages (i18n): if locale is not specified, "accept-language" header is used to try to determine the best one
author Goffi <goffi@goffi.org>
date Fri, 12 Apr 2019 14:08:02 +0200
parents ea0caa7b1bcc
children 469d0de8da0e
line wrap: on
line diff
--- a/libervia/server/pages.py	Fri Apr 12 14:06:50 2019 +0200
+++ b/libervia/server/pages.py	Fri Apr 12 14:08:02 2019 +0200
@@ -1411,6 +1411,28 @@
 
         return data
 
+    def setBestLocale(self, request):
+        """Guess the best locale when it is not specified explicitly by user
+
+        This method will check "accept-language" header, and set locale to first
+        matching value with available translations.
+        """
+        accept_language = request.getHeader("accept-language")
+        if not accept_language:
+            return
+        accepted = {a.strip() for a in accept_language.split(',')}
+        available = [unicode(l) for l in self.host.renderer.translations]
+        for lang in accepted:
+            lang = lang.split(';')[0].strip().lower()
+            if not lang:
+                continue
+            for a in available:
+                if a.lower().startswith(lang):
+                    session_data = self.host.getSessionData(request,
+                                                            session_iface.ISATSession)
+                    session_data.locale = a
+                    return
+
     def renderPartial(self, request, template, template_data):
         """Render a template to be inserted in dynamic page
 
@@ -1493,6 +1515,9 @@
                         locale = None
                     session_data.locale = locale
 
+            # if locale is not specified, we try to find one requested by browser
+            if session_data.locale is None:
+                self.setBestLocale(request)
 
         d = defer.Deferred()
         d.addCallback(self._checkAccess, request)