简体   繁体   English

在模板页面时重定向

[英]redirect while templating page

In Flask, how do you redirect to a different page while rendering a template? 在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")) causes the full page that would be templated and displayed to instead appear in the URL: return redirect(render_template("bar.html", title="Bar"))导致将被模板化并显示的整个页面显示在URL中:

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

This results in a 404 error because this page doesn't exist. 由于此页面不存在,因此会导致404错误。

I've tried redirect(url_for('bar')) but I need to pass Jinja2 variables to url_for and have it template the page. 我已经尝试过redirect(url_for('bar'))但是我需要将Jinja2变量传递给url_for并将其模板化为页面。

For redirecting you want a URL 对于重定向,您需要一个URL

return redirect(url_for('bar'))

You'll need to import url_for from Flask. 您需要从Flask导入url_for If you need to pass additional variables you should put them in as parameters 如果需要传递其他变量,则应将它们作为参数放入

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

then 然后

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM