如何创建到另一个html页面的链接?

30

我在一个页面上有一个表单,我想将其提交到另一个页面。我无法弄清如何创建到第二个页面的链接。

项目布局:

Fileserver/
    config.py
    requirements.txt
    run.py
    setup.py
    app/
        __init__.py
        static/
            css/
            img/
            js/
        templates/
            formAction.html
            formSubmit.html
            index.html

__init__.py:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    ip = request.remote_addr
    return render_template('index.html', user_ip=ip)

index.html:

<!DOCTYPE html>
<html lang="en">
<body>
    <ul>
        <li><a href="/formSubmit.html">Check Out This Form!</a>
    </ul>
</body>
</html>

没有问题,我可以在localhost:5000/上查看页面。

我还尝试过:

<a href="{{ url_for('templates', 'formSubmit") }}"></a>

以及:

<a href="{{ url_for('formSubmit') }}"></a>

我错过了什么?

2个回答

75

url_for可以生成指向应用程序中定义的路由的URL。在模板文件夹中不应该有原始的HTML文件被服务,也不应该有这样的文件。每个模板都应该是由Jinja渲染的东西。您想要显示或提交表单的每个位置都应该由应用程序上的路由处理和生成。

在这种情况下,您可能希望有一个路由来同时在GET上呈现表单并在POST上处理表单提交。

__init__.py

from flask import Flask, request, url_for, redirect, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/cool_form', methods=['GET', 'POST'])
def cool_form():
    if request.method == 'POST':
        # do stuff when the form is submitted

        # redirect to end the POST handling
        # the redirect can be to the same route or somewhere else
        return redirect(url_for('index'))

    # show the form, it wasn't submitted
    return render_template('cool_form.html')

templates/index.html:

<!doctype html>
<html>
<body>
    <p><a href="{{ url_for('cool_form') }}">Check out this cool form!</a></p>
</body>
</html>

templates/cool_form.html:

<!doctype html>
<html>
<body>
    <form method="post">
        <button type="submit">Do it!</button>
    </form>
</html>

我不知道你的表单和路由实际上是做什么的,所以这只是一个例子。


如果你需要链接静态文件,请将它们放在static文件夹中,然后使用以下代码:

url_for('static', filename='a_picture.png')

1
我刚刚发现的是,如果我不在 href 中加括号,它就可以工作了。我还创建了一个链接来返回上一页。
@app.route('/blog')
def blog():
    return '<h1>These are my thoughts on <a href=blog/2020/dogs>dogs</a></h1>'

@app.route('/blog/2020/dogs')
def blog2():
    return '<h3>these are my dogs <a href=../../blog>home</a></h3>'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接