2016-06-08 117 views
-1

在Flask中,如何在呈現模板時重定向到其他頁面?模板重定向頁面

@app.route('/foo.html', methods=['GET', 'POST']) 
def foo(): 
    if request.method == "POST": 
     x = request.form['x'] 
     y = request.form['y'] 
     if x > y: 
      return redirect(render_template("bar.html", title="Bar")) 
     else: 
      return render_template("foo.html", title="Foo") 

    return render_template("foo.html", title="Foo") 


@app.route('/bar.html') 
def bar(): 
    return render_template("bar.html", title="Bar") 

return redirect(render_template("bar.html", title="Bar"))導致整個頁面將被模板和顯示,而不是出現在URL:

http://localhost:5000/<!DOCTYPE html><html><head><title>Bar</title></head>...

這導致404錯誤,因爲該頁面不存在。

我試過redirect(url_for('bar'))但我需要將Jinja2變量傳遞給url_for並讓它爲頁面模板。

回答

2

對於重定向你想有一個URL

return redirect(url_for('bar')) 

你需要從瓶進口url_for。如果您需要通過額外的變量,你應該把它們作爲參數

somevalue = 1 
return redirect(url_for('bar', somevar=somevalue)) 

然後

@app.route('/bar/<somevar>') 
def bar(somevar): 
    # do something with somevar probably 
    return render_template("bar.html", title="Bar") 
+0

我需要傳遞將在一個bar.html作爲模板Jinja2的變量, 如。替換' {{title}}'與'' 您的建議方法無效。 –

+0

當然是的。將標題作爲變量傳遞,或者傳遞一個變量來告訴它設置了什麼標題。重定向生成301或302代碼的瀏覽器,你根本沒有返回模板。 – Cfreak