【问题标题】:how to import a html template in Flask? [duplicate]如何在 Flask 中导入 html 模板? [复制]
【发布时间】:2018-10-18 02:33:16
【问题描述】:
【问题讨论】:
标签:
html
css
templates
flask
【解决方案1】:
您应该将index.html 放在templates 文件夹中,并将其他所有内容放在static 文件夹中。
那么,在你application.py你可以使用:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
在 index.html 文件中,您可以使用 url_for 方法将所有链接作为该资源的路径:
<link rel=stylesheet type=text/css href="{{ url_for('static/css', filename='style.css') }}">
<link rel="stylesheet" href="{{ url_for('static/font-awesome/', filename='font-awesome.min.css') }}">
【解决方案2】:
将图像文件放入静态目录。不过,您也可以使用图像实际存在的静态路径。
文件结构:
app.py
static
|----your_Image.jpg
templates
|----index.html
那么 app.py 会是这样的
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/index', methods=['GET', 'POST'])
def lionel():
return render_template('index.html')
if __name__ == '__main__':
app.run()
在模板中 Index.html 看起来像
<html>
<head>
</head>
<body>
<h1>Hi Lionel Messi</h1>
<img src="{{url_for('static', filename='your_image.jpg')}}" />
</body>
</html>
这种方式可确保您不会为静态资产硬编码 URL 路径。