2016-06-13 2 views
1

나는 다중 언어 사이트 (EN 및 FR)를 만들고 있으며 사용자가 그렇게 선택하면 앞뒤로 번갈아 가며 전환해야합니다. Flask-Babel을 사용하고 있는데 번역 및 토글이 제대로 작동하고 있지만 URL도 번역해야합니다.Flask-Babel 다중 언어 URL 라우팅

다음과
@main.route('/accueil') 
@main.route('/home') 
def index(): 
    return render('index.html', {}) 

@main.route('/a-propos-de-nous') 
@main.route('/about-us') 
def about(): 
    return render('about.html', {}) 

언어를 잡아 토글되는 코드의 나머지 부분이 될 때 :

app = Flask(__name__, static_folder=settings.STATIC_ROOT) 
main = Blueprint('main', __name__, url_prefix='/language/<lang_code>') 

@app.url_defaults 
def set_language_code(endpoint, values): 
    if 'lang_code' in values or not session['lang_code']: 
     return 
    if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): 
     values['lang_code'] = session['lang_code'] 

@app.url_value_preprocessor 
def get_lang_code(endpoint, values): 
    if values is not None: 
     session['lang_code'] = values.pop('lang_code', None) 

@app.before_request 
def ensure_lang_support(): 
    lang_code = session['lang_code'] 
    if lang_code and lang_code not in app.config['SUPPORTED_LANGUAGES'].keys(): 
     return abort(404) 

@babel.localeselector 
def get_locale(): 
    if session.get('lang_code') is None: 
     session['lang_code'] = request.accept_languages.best_match(app.config['SUPPORTED_LANGUAGES'].keys()) 
    return session['lang_code'] 

템플릿 저는 현재 영어와 프랑스어 URL을 함께, 그래서처럼 내 URL 경로를 감쌌다 번역 UR로 전환 나는 파이썬/플라스크에 약간의 경험을 가지고

{% if session['lang_code']=='en' %} 
    {% set new_lang_code='fr' %} 
{% else %} 
    {% set new_lang_code='en' %} 
{% endif %} 
<li><a href="{{ request.path|replace("/"+session['lang_code']+"/", "/"+new_lang_code+"/") }}">{{ _('Fr') }}</a></li> 

... 나는 최선의 방법으로 어려움을 겪고 오전 : 사용자가 링크를 클릭은 언어를 변경하는 경우 다음과 같습니다 엘. 이 일을 어떻게 하죠? 모든 정보가 감사하겠습니다. 미리 감사드립니다.

답변

0

나는 해결책을 찾았습니다!

@main.route('accueil', endpoint="index_fr") 
@main.route('home', endpoint="index_en") 
def index(): 
    return render('index.html', {}) 

@main.route('a-propos-de-nous', endpoint="about_fr") 
@main.route('about-us', endpoint="about_en") 
def about(): 
    return render('about.html', {}) 

이이 텍스트의 나머지처럼 나를 URL 엔드 포인트를 번역 바벨을 사용할 수 있도록 허용하고, 언어와 함께 종료 정확한 URL을 잡아 : 그래서 같은 URL 경로에 엔드 포인트를 추가했다 세션의 코드 토글은 다음과 같이 작동합니다.

{% if session['lang_code']=='en' %} 
    {% set new_lang_code='fr' %} 
{% else %} 
    {% set new_lang_code='en' %} 
{% endif %} 

<li><a href="{{ url_for(request.endpoint|replace("_"+session['lang_code'], "_"+new_lang_code))|replace("/"+session['lang_code']+"/", "/"+new_lang_code+"/") }}">{{ _('Fr') }}</a></li>