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.
2 Answers
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 named stack.html
there, so there exists a file templates/stack.html
.
Code sample
from jinja2 import Environment, FileSystemLoader
from babel.support import Translations
locale_dir = "i18n"
msgdomain = "html"
list_of_desired_locales = ["cs", "en"]
loader = FileSystemLoader("templates")
extensions = ['jinja2.ext.i18n', 'jinja2.ext.autoescape', 'jinja2.ext.with_']
translations = Translations.load(locale_dir, list_of_desired_locales)
env = Environment(extensions=extensions, loader=loader) # add any other env options if needed
env.install_gettext_translations(translations)
template = env.get_template("stack.html")
rendered_template = template.render()
The rendered_template
contains the rendered HTML content now, probably in "cs" locale.

- 42,725
- 12
- 101
- 98

- 931
- 10
- 22
-
8but how do you control the language? I was expecting to be able to pass something like `template.render(locale='en')` – Emil Burzo Dec 11 '19 at 14:12
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

- 5,788
- 4
- 29
- 40

- 31
- 1
-
The link is now out-dated. And I wonder if it is still working if I use it from `web.archive.org` ? And how do I create the `messages.pot` file? – Roland Aug 08 '23 at 11:08