Flask-YAMLI18N is an i18n translation support for Flask which is based on PyYAML. But, why not use gettext? Because gettext may need to install additional software (on Windows) which I don’t like.
Flask-YAMLI18N is simple and only for translating text (without timezone support). PS, this is from my personal project, so you can choose to use it or not. You can try this great extension Flask_Babel.
Note: Flask-YAMLI18N requires Python 2.6+ (uses string.format syntax).
Install the extension with one of the following commands::
$ easy_install flask-yamli18n
or alternatively if you have pip installed:
$ pip install flask-yamli18n
| YAML_LOCALE_PATH | Define the location folder for yml files. (default is locales) |
| YAML_RELOAD | If reload the translation when files modified. (default is False) |
In your Flask application file (e.g. hello.py):
from flask import Flask, session, request
from flask.ext.yamli18n import YAMLI18N
app = Flask(__name__)
y18n = YAMLI18N(app)
# or later
# y18n = YAMLI18N()
# y18n.init_app(app)
t = y18n.t # for short
# default translation files folder is 'locales'
# app.config['YAML_LOCALE_PATH'] = 'locales'
app.jinja_env.filters['t'] = t
# put lang to your session
@app.before_request
def load_lang():
if 'lang' not in session:
session['lang'] = request.accept_languages.best
Example folder structure:
/hello.py
/locales
/default
/en.yml
/zh.yml
/blueprint_a
/en.yml
/zh.yml
the blueprint_a is get from:
mod = Blueprint('blueprint_a', __name__)
@mod.route('/')
def index():
return render_template('hello.html')
suppose you have a users blueprint, then the structure is:
/default
/en.yml
/zh.yml
/users
/en.yml
/zh.yml
locales/default/en.yml example:
hello: Hello # or 'Hello' or "Hello"
hello_world: "Hello, World!"
In your template file (e.g. hello.html):
<!doctype html>
<title>{{ 'hello'|t }}</title>
{{ 'hello_world'|t }}
The output is:
<!doctype html>
<title>Hello</title>
Hello, World!
get the locales and reload setting:
load the translations to self.ymls
text follows the formats:
in users/en.yml:
.edit:
name: Hello, there
used to provide additional params after translation
e.g. the translation string is:
hello_world: {user}, Hello world
then you can do this in your template:
{{ 'hello_world'|t(user='Lix') }}
you will get:
Lix, Hello world
(tiny improvement, released on 2015-Jan-23)