You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Jinja2模板中的HTML按钮跳转FastAPI路由?

实现FastAPI前端按钮跳转路由的几种方法

方法1:用<a>标签模拟按钮(无需JS)

这是最简洁的实现方式,直接用<a>标签指定目标路由,再通过CSS改成按钮样式,点击就会跳转到/tasks:

<a href="/tasks" style="padding: 8px 16px; background-color: #007bff; color: white; border: none; border-radius: 4px; text-decoration: none; cursor: pointer;">查看所有任务</a>

样式可以根据需求调整,核心是href="/tasks"指定跳转路径。

方法2:用<button>标签+JavaScript

如果必须用原生按钮,给按钮添加点击事件,通过JS修改页面地址实现跳转:

内联事件写法

<button onclick="window.location.href='/tasks'">查看所有任务</button>

分离式写法(更规范)

把JS逻辑抽出来,便于维护:

<button id="viewTasksBtn">查看所有任务</button>

<script>
document.getElementById('viewTasksBtn').addEventListener('click', function() {
    window.location.href = '/tasks';
});
</script>

确认后端根路由配置

确保你的根路由正确返回index.html模板,示例代码如下:

from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates

app = FastAPI()
# 假设HTML文件放在项目根目录的templates文件夹下
templates = Jinja2Templates(directory="templates")

@app.get("/")
def root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

内容的提问来源于stack exchange,提问作者lazlomeli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 19:55:25