【问题标题】:redirect while templating page模板页面时重定向
【发布时间】:2016-06-08 01:29:47
【问题描述】:

在 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 并将其作为页面模板。

【问题讨论】:

    标签: python html web flask


    【解决方案1】:

    为了重定向你想要一个 URL

    return redirect(url_for('bar'))
    

    您需要从 Flask 导入 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")
    

    【讨论】:

    • 我需要传递将在 bar.html 中模板化的 Jinja2 变量,例如。将 &lt;title&gt;{{ title }}&lt;/title&gt; 替换为 &lt;title&gt;Bar&lt;/title&gt; 您建议的方法不起作用。
    • 是的,当然可以。将您的标题作为变量传递,或者传递一个告诉它要设置什么标题的变量。重定向会在浏览器中生成 301 或 302 代码,您根本不会返回模板。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 2013-03-18
    相关资源
    最近更新 更多