Nat*_*ong 4 rendering ruby-on-rails ruby-on-rails-3
我正在使用PDFKit中间件来呈现PDF.这是它的作用:
一般来说,我想要那种行为.但我有一个案例,我实际上需要我的应用程序根据请求PDF的事实呈现不同的内容.
PDFKit为我提供了一个标记来检测它是否计划呈现我的响应:它设置env["Rack-Middleware-PDFKit"]
为true.
但我需要告诉Rails,基于该标志,我希望它呈现show.pdf.haml
.我怎样才能做到这一点?
弄清楚了.根据Rails源代码,request.format = 'pdf'
将手动将响应格式设置为PDF.这意味着Rails将呈现,例如show.pdf.haml
.
但是,现在PDFKit不会将响应转换为实际的PDF,因为Content-Type
当我们实际上只生成HTML时,标题表示它已经是PDF.所以我们还需要覆盖Rails的响应标头,说它仍然是HTML.
这个控制器方法处理它:
# By default, when PDF format is requested, PDFKit's middleware asks the app
# to respond with HTML. If we actually need to generate different HTML based
# on the fact that a PDF was requested, this method reverts us back to the
# normal Rails `respond_to` for PDF.
def use_pdf_specific_template
return unless env['Rack-Middleware-PDFKit']
# Tell the controller that the request is for PDF so it
# will use a PDF-specific template
request.format = 'pdf'
# Tell PDFKit that the response is HTML so it will convert to PDF
response.headers['Content-Type'] = 'text/html'
end
Run Code Online (Sandbox Code Playgroud)
这意味着控制器操作如下所示:
def show
@invoice = Finance::Invoice.get!(params[:id])
# Only call this if PDF responses should not use the same templates as HTML
use_pdf_specific_template
respond_to do |format|
format.html
format.pdf
end
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1634 次 |
最近记录: |