dhy*_*sba 4 python flask python-babel
我开发多语言网站。页面的 URI 如下所示:
/RU/about
/EN/about
/IT/about
/JP/about
/EN/contacts
Run Code Online (Sandbox Code Playgroud)
在 jinja2 模板中我写道:
<a href="{{ url_for('about', lang_code=g.current_lang) }}">About</a>
Run Code Online (Sandbox Code Playgroud)
我必须在所有url_for调用中编写 lang_code=g.current_lang 。
是否可以隐式lang_code=g.current_lang传递url_for?并且只写 {{ url_for('about') }}
我的路由器看起来像:
@app.route('/<lang_code>/about/')
def about():
...
Run Code Online (Sandbox Code Playgroud)
用于app.url_defaults在构建 url 时提供默认值。用于app.url_value_preprocessor自动从 url 中提取值。有关 url 处理器的文档对此进行了描述。
@app.url_defaults
def add_language_code(endpoint, values):
if 'lang_code' in values:
# don't do anything if lang_code is set manually
return
# only add lang_code if url rule uses it
if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
# add lang_code from g.lang_code or default to RU
values['lang_code'] = getattr(g, 'lang_code', 'RU')
@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
# set lang_code from url or default to RU
g.lang_code = values.pop('lang_code', 'RU')
Run Code Online (Sandbox Code Playgroud)
现在url_for('about')会产生/RU/about, 并g.lang_code在访问 url 时自动设置为 RU。
Flask-Babel为处理语言提供了更强大的支持。