【问题标题】:Rails4: Template is missing error with PDFKitRails4:PDFKit 的模板丢失错误
【发布时间】:2016-09-11 00:33:28
【问题描述】:

我想生成 PDF 文件,所以我尝试使用 PDFKit 但失败了。

单击链接时显示以下错误。

ActionView::MissingTemplate (Missing template /show with {:locale=>[:en], :formats=>[:pdf], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/usr/local/rvm/gems/ruby-2.3.0/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates"
  * "/home/ubuntu/workspace/app/views"
  * "/usr/local/rvm/gems/ruby-2.3.0/gems/web-console-2.0.0.beta3/app/views"

schedules\show.html.erb

<% provide(:title, @schedule.title) %>
<%= render @schedules %>

时间表\_schedule.html.erb

...
    <%= link_to "PDF", schedule_path(schedule.id, format: "pdf"), class: "btn btn-sm btn-default" %>
...

schedules_controller.rb

...
respond_to do |format|
  format.html # show.html.erb
  format.pdf do
    html = render_to_string template: "show"

    pdf = PDFKit.new(html, encoding: "UTF-8")

    send_data pdf.to_pdf,
      filename:    "#{@scheudles.id}.pdf",
      type:        "application/pdf",
      disposition: "inline"
  end
end
...

虽然我创建了show.pdf.erb_schedule.pdf.erb,它们的内容与html.erb相同,但结果是一样的。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 pdf pdfkit


    【解决方案1】:

    您获得Missing template /show 的原因是因为控制器使用template: "show" 不够具体,因此rails 无法知道在您的视图文件夹中的哪个位置可以找到show 文件。

    你可以在你的错误中看到这一点的证据,它说它在../app/views 中搜索了show。您需要使用模板父文件夹以及模板名称。

    改一下

    format.pdf do
      html = render_to_string template: "show"
      ...
    end 
    

    到这里

    format.pdf do
      html = render_to_string template: "schedules/show.html.erb"
      ...
    end
    

    【讨论】:

    • 感谢您的回答,@MilesStanfield。虽然我改成schedules/show.html.erb,还是出现如​​下错误。 RuntimeError (command failed (exitstatus=0): /usr/local/rvm/gems/ruby-2.3.0/bin/wkhtmltopdf --encoding UTF-8 --page-size A4 --margin-top 0.25in --margin-right 1in --margin-bottom 0.25in --margin-left 1in - -):
    • 您现在离您更近了一步 :) 我帮助您克服了之前的错误,并希望您能给予支持。祝你好运!
    • 感谢您的评论和回答,@MilesStanfield。我的问题可能是您提到的另一个原因。如果您可以查看另一个帖子,将不胜感激 (stackoverflow.com/questions/39471547/…)
    • 我看了。但很抱歉,我没有这个问题的答案
    【解决方案2】:

    只需更改:action =&gt; "show.html.erb"

    html = render_to_string(:layout =&gt; false , :action =&gt; "show.pdf.erb")

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 2013-11-03
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      相关资源
      最近更新 更多