Search code examples
pythongoogle-app-engineinternationalizationpython-babel

Internationalization with python gae, babel and i18n. Can't output the correct string


jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),extensions=['jinja2.ext.i18n'], autoescape = True)
jinja_env.install_gettext_translations(i18n)

config['webapp2_extras.i18n'] = {
    'translations_path': 'locale',
    'template_path': 'views'
}

app = webapp2.WSGIApplication([
    ('/', MainController.MainPageHandler)
], config=config, debug=True)

In the messages.po file.

"Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" "POT-Creation-Date: 2013-01-19 19:26+0800\n" "PO-Revision-Date: 2013-01-19 19:13+0800\n" "Last-Translator: FULL NAME \n" "Language-Team: en_US \n" "Plural-Forms: nplurals=2; plural=(n != 1)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 0.9.6\n"

#~ msgid "Hello-World"

#~ msgstr "Hello World"

In the handler:

from webapp2_extras import i18n

from webapp2_extras.i18n import gettext as _

class MainPageHandler(Handler.Handler):
    def get(self):
        locale = self.request.GET.get('locale', 'en_US')
        i18n.get_i18n().set_locale(locale)
        logging.info(locale)
        message = _('Hello-World')
        logging.info(message)
        self.render("main.html")

In the html file:

<div id="main">

    {{ _("Hello-World") }}
</div>

When navigate to the webpage, it returns the string "Hello-World" instead of "Hello World". I don't know what's wrong. Anyone can help?


Solution

  • Couple of things that might be wrong, or might just be missing from the description...

    the default 'domain' with webapp2 translation is 'messages', not 'message', so if your file is actually 'message.po' as you typed it, then that needs to change.

    Secondly, the translation works off the compiled .mo file, not the .po, so if you haven't run the compile step (pybabel compile -f -d ./locale), you need to do that. You should have a file at locale/en_US/LC_MESSAGES/messages.mo