如何使用url_读取templates文件夹中的文件?

2024-06-14 01:45:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读取位于路径:templates/print.html中的文件print.html。在

所以,我用url_for()来指代它如下:

{{ url_for('templates', filename='print.html') }}

但是,我得到一个错误,如下所示:

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

这怎么了?在

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

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


Tags: 文件路径文件夹noneurlforhtml错误
1条回答
网友
1楼 · 发布于 2024-06-14 01:45:26

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

您可以为print.html建立路由:

@app.route('/print')
def print():
    return render_template('print.html')

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

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

有一个方便的Flask blueprint模式非常有用,如果您只是渲染一堆模板,而不需要任何视图逻辑,see it here

相关问题 更多 >