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?
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 atlocale/en_US/LC_MESSAGES/messages.mo
Thanks, @tipsywacky, I was a little lost with jinja2, babel and GAE, and your code put me on the right path.
I want to share my code for other "stackers", in which you can appreciate a strange thing: don't know why, but I don't need to setup a config var to make all working.
With only this code and your HTML file (and the message.mo files compiled):
my app makes the translation of the logging text and of the HTML text.
That's wonderful, I spent the full day searching for a way to do localization and finally I got it.
The only thing I don't understand is your config var. Why I don't need it?
Alright, figured out what's wrong.
In the messages.po file, I put down
#: gettext_example.py:16
at the top ofmsgid "Hello-World"
. Then re-compile it, and it works.