如何设置flask中index.html模板的位置
时间: 2024-05-14 13:18:50 浏览: 121
在 Flask 中使用模板引擎渲染 HTML 页面时,默认情况下会在应用程序的 `templates` 目录下查找模板文件。如果您想要修改默认的模板目录,可以在 Flask 中使用 `TemplateFolder` 类来设置模板文件的位置。
以下是一个示例代码:
```python
from flask import Flask, render_template
from jinja2 import TemplateNotFound
app = Flask(__name__, template_folder='/path/to/templates')
@app.route('/')
def index():
try:
return render_template('index.html')
except TemplateNotFound:
return 'Page not found', 404
if __name__ == '__main__':
app.run()
```
在上面的示例中,将模板目录设置为 `/path/to/templates`,而不是默认的 `templates` 目录。在 `index()` 函数中,使用 `render_template()` 函数来渲染 `index.html` 模板文件。如果模板文件不存在,将返回一个 404 错误页面。
需要注意的是,如果您使用的是 Flask 的 Blueprint,同样可以使用 `template_folder` 参数来设置模板目录。例如:
```python
from flask import Blueprint, render_template
bp = Blueprint('example', __name__, template_folder='/path/to/templates')
@bp.route('/')
def index():
return render_template('index.html')
```
在上面的示例中,将模板目录设置为 `/path/to/templates`,然后在 `index()` 函数中渲染 `index.html` 模板文件。
阅读全文
相关推荐


















