2015-11-18 60 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爲處理語言提供了更強大的支持。

相關問題