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'])

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

  1. Generally, its considered best to put all imports at the top of the file not scattered throughout
  2. Rather then importing a bunch of stuff to use once, use self.gettext = translation.gettext etc
  3. Why empty lines after class, but nowhere else? I'd but a blank line before the start of a class and not inside.
  • \$\begingroup\$ Thanks. I'm still learning conventions and how to code python so I didn't totally know how to do it. \$\endgroup\$
    – Niklas R.
    Nov 3 '11 at 4:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.