daily pastebin goal
27%
SHARE
TWEET

Untitled

a guest Aug 17th, 2018 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. i18n with jinja2   GAE
  2. import jinja2
  3. from django.utils import translation
  4. from django.utils.translation import gettext, ngettext, ugettext, ungettext, get_language, activate
  5. class DjangoTranslator(object):
  6.  
  7.     def __init__(self):
  8.         self.gettext = gettext
  9.         self.ngettext = ngettext
  10.         self.ugettext = ugettext
  11.         self.ungettext = ungettext
  12. from jinja2 import Environment, FileSystemLoader
  13. class DjangoEnvironment(jinja2.Environment):
  14.  
  15.     def get_translator(self, context):
  16.         return DjangoTranslator()
  17.  
  18. jinja_environment = DjangoEnvironment(
  19.     loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.i18n'])
  20. jinja_environment.install_gettext_translations(translation)
  21.    
  22. from django.utils import translation
  23.  
  24. class I18NHandler(webapp2.RequestHandler):
  25.  
  26.     def render_template(self, file, template_args):
  27.         path = os.path.join(os.path.dirname(__file__), 'templates',
  28.                             file)
  29.         self.response.out.write(template.render(path, template_args))
  30.  
  31.     def initialize(self, request, response):
  32.         webapp2.RequestHandler.initialize(self, request, response)
  33.         self.request.COOKIES = Cookies(self)
  34.         self.request.META = os.environ
  35.         self.reset_language()
  36.  
  37.     def reset_language(self):
  38.  
  39.         # Decide the language from Cookies/Headers
  40.  
  41.         language = translation.get_language_from_request(self.request)
  42.         translation.activate(language)
  43.         self.request.LANGUAGE_CODE = translation.get_language()
  44.  
  45.         # Set headers in response
  46.         self.response.headers['Content-Language'] = str(translation.get_language())
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top