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

Ruby on Rails处理PDF请求时渲染HTML模板及render_to_string报错求解

问题解决方案

报错核心原因

你在format.pdf响应块内调用渲染方法时,Rails默认会将当前响应格式上下文识别为pdf,即便指定formats: [:html],部分Rails版本仍会出现模板路径解析歧义,优先查找.pdf.erb后缀的模板,最终抛出ActionView::MissingTemplate错误。

修复方案

通用写法(无需硬编码模板路径)

先手动切换当前响应的格式上下文为html,再调用render_to_string渲染即可,同时可根据需求指定是否继承全局布局:

format.pdf do
  # 强制切换当前响应格式为html
  self.formats = [:html]
  # layout参数填写你HTML页面实际使用的布局名,不需要布局则填false
  html = render_to_string(layout: "application")

  kit = PDFKit.new(html, page_size: 'A4', orientation: 'Portrait')
  send_data(kit.to_pdf, filename: 'my_report.pdf', type: 'application/pdf; charset=utf-8', disposition: 'inline')
end

明确指定模板路径写法

如果上述写法仍有问题,可以直接硬编码指定模板的路径:

# 路径规则为 控制器名/动作名,例如动作在ReportsController下就写reports/my_report
html = render_to_string(template: "控制器名/my_report", formats: [:html], layout: "application")

注意事项

所有HTML模板依赖的实例变量、业务逻辑必须放在respond_to代码块之外,不要将变量赋值逻辑写在format.html块内,否则渲染HTML时会因为变量缺失报错。

内容的提问来源于stack exchange,提问作者Tonči D.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:36:04