【问题标题】:How do I create a link to another html page?如何创建指向另一个 html 页面的链接?
【发布时间】:2014-12-18 04:35:31
【问题描述】:

我在一个页面上有一个表单,我想提交到另一个页面。我不知道如何创建指向第二页的链接。

项目布局:

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>

我错过了什么?

【问题讨论】:

    标签: python flask


    【解决方案1】:

    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')
    

    【讨论】:

      【解决方案2】:

      所以我刚刚发现,如果我不将 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>'
      

      【讨论】:

        猜你喜欢
        • 2015-06-05
        • 1970-01-01
        • 1970-01-01
        • 2016-12-23
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 2020-10-27
        • 1970-01-01
        相关资源
        最近更新 更多