How can I use jinja2 with babel outside a flask application. Supposing that I have locale dir which is populated using pybabel command. I want to load translation files and translate my template files.
How to use jinja2 and its i18n extension (using babel) outside flask
7.1k views Asked by Ali At
2
There are 2 answers
1
On
This works great! Thanks.
I. jinja2 dependency MarkupSafe
II. Python babel dependency ytz
See for these steps at http://tlphoto.googlecode.com/git/jinja2_i18n_howto.txt
Create the folder structure (no whitespace after the commas!!!)
mkdir -pv ./lang/{en_US,zh_CN,fa_IR,es_VE,de_DE,ja_JP}/LC_MESSAGES/
Extract
pybabel -v extract -F babel.config -o ./lang/messages.pot ./
Init/Update
3.1 Init
pybabel init -l zh_CN -d ./lang -i ./lang/messages.pot
3.2 Update
pybabel update -l zh_CN -d ./lang -i ./lang/messages.pot
Compile
pybabel compile -f -d ./lang
I found the solution. Here's how you can use jinja2/babel without flask integration.
Preconditions
Preconditions are described just to complete the example, all of them can have other values or names.
You use message domain named "html" for messages (domain is arbitrary name, default is "message").
There is a directory "i18n" with translated and compiled messages (e.g. with a file
i18n/cs/LC_MESSAGES/html.mo
).You prefer to render your templates using "cs" or "en" locale.
The templates are located in directory
templates
and there exists a jinja2 template namedstack.html
there, so there exists a filetemplates/stack.html
.Code sample
The
rendered_template
contains the rendered HTML content now, probably in "cs" locale.