2015-11-18 59 views
2

我开发了多语言网站。 网页有URI是这样的:如何传递给url_for默认参数?

/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(): 
... 

回答

3

使用app.url_defaults建立一个URL时提供的默认值。使用app.url_value_preprocessor自动从网址中提取值。这在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,并访问URL时g.lang_code将被自动设置为RU。


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

相关问题