You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用url_for读取templates文件夹文件?BuildError报错解决

解决Flask中用url_for访问templates文件夹文件的问题

首先得理清一个核心概念:Flask里的templates文件夹是用来存放动态模板的,这类文件需要通过视图函数调用render_template渲染后返回给客户端,而不是像静态资源那样直接通过url_for指向文件路径。你之前遇到的BuildError,就是因为templates并不是Flask识别的有效端点(url_for的第一个参数得是视图函数名或者像static这种内置特殊端点)。

正确的解决步骤:

  1. 创建对应的视图函数
    在你的Flask应用代码里,添加一个路由视图来渲染这个print.html模板:

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/print')
    def render_print_page():
        # 这里会自动从templates文件夹里找print.html并渲染
        return render_template('print.html')
    
  2. 在模板中用url_for指向视图端点
    现在你就可以在其他模板里用url_for指向这个视图函数的名称(也就是端点)来生成正确的URL了:

    {{ url_for('render_print_page') }}
    

额外说明:

如果你的print.html其实不需要动态渲染(就是纯静态HTML),那更简单的方式是把它移到static文件夹里,这样你之前用的{{ url_for('static', filename='print.html') }}就能直接用。但既然你明确要放在templates里,那通过视图函数转发就是标准做法。

内容的提问来源于stack exchange,提问作者Houy Narun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:09:41