3

我开发多语言网站。页面有这样的 URI:

/RU/about

/EN/about

/IT/about

/JP/about

/EN/contacts

在 jinja2 模板中我写:

<a href="{{ url_for('about', lang_code=g.current_lang) }}">About</a>

我必须在所有url_for调用中编写 lang_code=g.current_lang 。

是否可以隐式传递lang_code=g.current_lang给?url_for并且只写 {{ url_for('about') }}

我的路由器看起来像:

@app.route('/<lang_code>/about/')
def about():
...
4

1 回答 1

4

用于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')

现在url_for('about')将产生/RU/about,并g.lang_code在访问 url 时自动设置为 RU。


Flask-Babel为处理语言提供了更强大的支持。

于 2015-11-18T15:03:27.733 回答