如何使用 url_for 读取模板文件夹中的文件?

Hou*_*run 2 python flask

我试图读取print.html位于 path: 中的文件templates/print.html

所以,我曾经url_for()这样称呼它:

{{ url_for('templates', filename='print.html') }}
Run Code Online (Sandbox Code Playgroud)

但是,我收到如下回溯错误:

BuildError: ('templates', {'filename': 'print.html'}, None)

这有什么问题?

如果我使用{{ url_for('static', filename='print.html') }},它只是工作找到。但是,我尝试读取的static文件不在文件夹中,而是在文件夹中templates/print.html

如何使用url_for()读取文件夹print.html中的templates文件?谢谢。

Doo*_*beh 5

我首先要说 - 如果您尝试url_for使用模板,很可能您误解了一个概念。但是,假设您知道渲染模板和静态资产之间的区别:

您可以为以下对象构建一条路线print.html

@app.route('/print')
def print():
    return render_template('print.html')
Run Code Online (Sandbox Code Playgroud)

这将使您能够url_for('print')获取解析的 url,并且print.html模板中的任何动态组件都将呈现为静态 html。

否则,如果print.html确实是静态的——只需将其移动到static文件夹中,然后url_for('static', filename='print.html')按照您的指示使用。

如果您只是渲染一堆模板并且不需要任何视图逻辑,有一个方便的 Flask 蓝图模式很有用,请在此处查看