2015-01-28 2 views
1

내 앱에 제품 모델이 있습니다. 일부 제품에는 카테고리가 있지만 그렇지 않은 제품도 있습니다. 내 페이지 중 하나에 나는이 것이이 처리라우팅 할 URL을 작성할 때 빈 매개 변수를 처리하십시오.

{% if row.category %} 
    <a href="{{ url_for("details_with_category", category=row.category, title=row.title) }}"> row.prod_title</a> 
{% else %} 
    <a href="{{ url_for("details_without_category", title=row.title) }}"> row.prod_title</a> 
{% endif %} 

견해 :

details_with_category
@app.route('/<category>/<title>', methods=['GET']) 
def details_with_category(category, title): 
    .... 
    return .... 

@app.route('/<title>', methods=['GET']) 
def details_without_category(title): 
    .... 
    return .... 

details_without_category 그냥 다른 URL로, 똑같은 일을합니다. URL을 생성 할 때 선택적 인수를 취하는 단일보기로보기를 결합하는 방법이 있습니까?

답변

3

선택적 인수에 기본값을 전달하여 동일한 함수에 여러 경로를 적용합니다.

@app.route('/<title>/', defaults={'category': ''}) 
@app.route('/<category>/<title>') 
def details(title, category): 
    #... 

url_for('details', category='Python', title='Flask') 
# /details/Python/Flask 

url_for('details', title='Flask') 
# /details/Flask 

url_for('details', category='', title='Flask') 
# the category matches the default so it is ignored 
# /details/Flask 

청소기 솔루션은 URL 형식이 일치되도록 단지 분류되지 않은 제품에 기본 범주를 할당하는 것입니다.

관련 문제