我开发多语言网站。
页面有这样的 URI:
/RU/about
/EN/about
/IT/about
/JP/about
/EN/contacts
在 jinja2 模板中,我写道:
<a href="{{ url_for('about', lang_code=g.current_lang) }}">About</a>
我必须全部写 lang_code=g.current_lang
url_for
调用。是否可以通过
lang_code=g.current_lang
至 url_for
隐含的?并且只写 {{ url_for('about') }}
我的路由器看起来像:
@app.route('/<lang_code>/about/')
def about():
...
最佳答案
使用 app.url_defaults
在构建 url 时提供默认值。使用 app.url_value_preprocessor
自动从 url 中提取值。这在 the docs about url processors 中有描述.
@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')
现在
url_for('about')
将产生 /RU/about
, 和 g.lang_code
访问 url 时将自动设置为 RU。Flask-Babel为处理语言提供更强大的支持。
关于flask - 如何传递给 url_for 默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33783131/