Python实现两个HTML之间的跳转
时间: 2024-03-02 15:51:25 浏览: 18
在Python中实现两个HTML之间的跳转,需要使用 Flask 这框架。
以下是简单的示例代码:
```python
from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run()
```
在这个示例中,我们定义了一个 Flask 应用,并且定义了两个路由,分别是根路由 '/' 和关于页面 '/about'。在每个路由函数中,我们使用 `render_template` 函数渲染对应的 HTML 模板。
在 HTML 模板中,我们可以使用 `<a>` 标签来实现两个 HTML 之间的跳转。例如,在 `home.html` 中加入以下代码:
```html
<a href="{{ url_for('about') }}">关于我们</a>
```
这个代码片段会在 `home.html` 页面中显示一个链接,当用户点击这个链接时,会跳转到 `about` 页面。其中,`url_for` 函数会根据路由函数的名称生成对应的 URL。
类似地,在 `about.html` 中加入以下代码:
```html
<a href="{{ url_for('home') }}">返回首页</a>
```
这个代码片段会在 `about.html` 页面中显示一个链接,当用户点击这个链接时,会跳转回 `home` 页面。