HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythondjangoMinor

i18n translator using Jinja2

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
jinja2i18nusingtranslator

Problem

I'm learning to Jinja2 and what's important in this case isn't speed but i18n translations and functionality. With Python 2.7, Jinja2 and not Django seems to preferred way to go, so I'm rewriting much of my project to use Jinja2 templates. We already had plenty of translations in .mo and .po files and wanted to keep use of those and we also want to make use of django's translation package. I found a way to use the Django translation libraries with Jinja2.

Could you review this code and comment if I can use it this way? My SDK is Google App Engine.

import jinja2
from django.utils import translation
from django.utils.translation import gettext, ngettext, ugettext, ungettext, get_language, activate
class DjangoTranslator(object):

    def __init__(self):
        self.gettext = gettext
        self.ngettext = ngettext
        self.ugettext = ugettext
        self.ungettext = ungettext
from jinja2 import Environment, FileSystemLoader
class DjangoEnvironment(jinja2.Environment):

    def get_translator(self, context):
        return DjangoTranslator()

jinja_environment = DjangoEnvironment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.i18n'])
jinja_environment.install_gettext_translations(translation)

Solution

I don't know jinja but I can give a few generic python pointers:

  • Generally, its considered best to put all imports at the top of the file not scattered throughout



  • Rather then importing a bunch of stuff to use once, use self.gettext = translation.gettext etc



  • Why empty lines after class, but nowhere else? I'd but a blank line before the start of a class and not inside.

Context

StackExchange Code Review Q#5767, answer score: 3

Revisions (0)

No revisions yet.