render_to_string does not find partials (PDFKit controller response)

我怕爱的太早我们不能终老 提交于 2019-12-05 01:52:15

I was running into this issue this morning and came across your question while looking for a solution.

Controller extract:

respond_to do |format|
  format.html
  format.pdf {
    html = render_to_string(:layout => false , :action => "constitution.pdf.haml")
    kit = PDFKit.new(html)
    kit.stylesheets << "#{Rails.root}/public/stylesheets/pdf.css"
    send_data(kit.to_pdf, :filename => "#{@organisation_name} Constitution.pdf",
      :type => 'application/pdf', :disposition => 'inline')        
    return
  }
end

constitution.pdf.haml extract:

=render :partial => 'shared/constitution'

Error:

Missing partial shared/constitution with {:locale=>[:en, :e   ...

After a while banging my head against a wall, I had a guess and changed constitution.pdf.haml to:

=render :partial => 'shared/constitution.html.haml'

I only know a tiny amount about Rails. Could it really be that (unlike my normal Haml views), PDFKit requires the file extension? That's fixed it for me!

You can also set :formats for render_to_string to prevent having to change your partial names.

html = render_to_string(:layout => false , :action => "show", :formats => :html)

This forces html, instead of pdf, format for the remained of the view rendering. Allowing you to use the same views/partials without change for HTML and PDF responses.

You should specify full path to your template I think:

html = render_to_string(:template => "my_view_folder_name/show.html.erb")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!