flask 自定义页面
时间: 2023-05-31 14:05:14 浏览: 63
在 Flask 中,可以通过自定义模板来创建自己的页面。
首先,需要创建模板文件,可以使用 Jinja2 模板语言。模板文件通常保存在 `templates` 文件夹中,例如 `templates/index.html`。
在模板文件中,可以使用变量、条件语句、循环语句等来渲染页面。例如:
```html
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ message }}</h1>
{% if user %}
<p>Welcome, {{ user }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
</body>
</html>
```
在 Flask 中,可以使用 `render_template` 函数来渲染模板。例如:
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', title='Home', message='Hello, Flask!')
if __name__ == '__main__':
app.run()
```
在上面的例子中,`render_template` 函数将 `templates/index.html` 渲染成 HTML 页面,并传递了 `title` 和 `message` 变量作为模板中的参数。
可以在 Flask 应用的路由函数中使用 `render_template` 函数来渲染不同的页面。例如:
```python
@app.route('/about')
def about():
return render_template('about.html', title='About', message='This is the about page.')
```