# i18n translator using Jinja2

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)


## 1 Answer

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.
• Thanks. I'm still learning conventions and how to code python so I didn't totally know how to do it. – Niklas Rosencrantz Nov 3 '11 at 4:51