Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jinja2 and its i18n extension (using babel) outside flask

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.

like image 213
Ali Avatar asked Sep 08 '13 12:09

Ali


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.

like image 124
Ali Avatar answered Oct 18 '22 14:10

Ali


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

  1. 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/

  2. Extract

    pybabel -v extract -F babel.config -o ./lang/messages.pot ./

  3. 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

  4. Compile

    pybabel compile -f -d ./lang

like image 32
Mike Chavez Avatar answered Oct 18 '22 15:10

Mike Chavez