flask - 如何传递给 url_for 默认参数?

标签 flask jinja2 translation url-for python-babel

我开发多语言网站。
页面有这样的 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_langurl_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/

相关文章:

python - Flask:操纵 View 参数的首选方式?

android - 旋转后的 OpenGL ES 2 翻译

c++ - QT_TR_NOOP : translation files are generated, 但从未使用过翻译后的字符串,为什么?

flask - 如何使用 oAuth2 保护 Flask-RESTPlus API?

google-analytics - Flask:如何防止 Google Analytics JS 在开发环境中运行?

python-3.x - 如何在 Windows 下从 PyCharm 中运行 Flask CLI

python - 如何优化 Flask 的 render_template() 模板

python - jinja2模板引擎中的这个 "-"是做什么的?

flask - jinja 是否支持宏中的多个 block ?

angular - 使用 Angular 从服务器动态获取翻译