【问题标题】:Flask - Make a button direct to another pageFlask - 使按钮重定向到另一个页面
【发布时间】:2020-08-20 19:56:27
【问题描述】:

在我的主页上,我有一个显示“Enter”的按钮

<button id="Enter" type="button" onclick="/profile" class="button">Enter</button>
</div>

我希望当单击此按钮时,它会指向“主页”页面

Python 代码:

@app.route('/', methods = ['GET', 'POST'])
def index():
    return render_template("main.html")

@app.route('/home', methods = ['GET', 'POST'])
def home():
    return render_template("test1.html")

如何做到这一点?谢谢

【问题讨论】:

    标签: python html flask button


    【解决方案1】:

    这是锚标签的工作。

    Jinja2(Flask 的模板渲染组件)允许您使用url_for 函数为给定的视图函数动态创建一个url。

    在你的情况下:

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

    使用您的代码,这将在浏览器中呈现为:

    <a href="/home">Home</a>
    

    即使您更改 app.route 装饰器函数中的端点,它也会使用正确的 URL 呈现。

    为了给它一个按钮的外观,我建议使用 Bootstrap 库。这可以通过在 HTML 模板的 head 中添加以下内容从 CDN 中包含:

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.0/css/bootstrap.min.css" integrity="sha256-/ykJw/wDxMa0AQhHDYfuMEwVb4JHMx9h4jD4XvHqVzU=" crossorigin="anonymous" />
    

    然后分配按钮样式就像在锚标记中添加class 属性一样简单:

    class='btn btn-primary'
    

    查看bootstrap docs中的其他可用类

    【讨论】:

    • 谢谢!唯一的问题是它应该是 {{ url_for('home') }} 而不是 {% url_for('home') %} :)
    • @peady 好地方!
    猜你喜欢
    • 2014-07-21
    • 1970-01-01
    • 2013-01-17
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2019-09-01
    相关资源
    最近更新 更多