guh*_*rak 6 ruby rendering ruby-on-rails wkhtmltopdf wicked-pdf
我尝试使用 gem wicked_pdf 将 Rails 视图转换为 pdf。但是当我像这样执行 render_to_string 时
ActionController::Base.new.render_to_string(template: "templates/pdf_meteo.html.erb", locals: {communaute_meteo_id: id}, layout: 'pdf')
Run Code Online (Sandbox Code Playgroud)
像这样的方法user_path
不起作用并返回未定义的方法错误...(请注意,如果我在 html 中呈现该页面,则该页面可以正常工作)如果有人可以帮助我!
您可以使用以下方法包含助手
ac = ActionController::Base.new
ac.view_context_class.include(ActionView::Helpers, ApplicationHelper)
ac.render_to_string(template: "templates/pdf_meteo.html.erb", locals: {communaute_meteo_id: id}, layout: 'pdf')
Run Code Online (Sandbox Code Playgroud)
小智 4
不幸的是,使用render_to_string
不会让您访问 Rails URL 帮助程序。locals
一种解决方法是使用以下方法将它们直接包含在传递到 PDF 模板的文件中url: Rails.application.routes.url_helpers
:
ActionController::Base.new.render_to_string(
template: "templates/pdf_meteo.html.erb",
locals: {url: Rails.application.routes.url_helpers, communaute_meteo_id: id}
layout: 'pdf'
)
Run Code Online (Sandbox Code Playgroud)
然后在 PDF 模板中您可以使用以下方式调用它们:
url.user_path
Run Code Online (Sandbox Code Playgroud)
请记住,默认情况下,_path
URL 帮助程序将是相对路径,而不是绝对路径。您可以改为使用_url
助手的版本,并host
以几种不同的方式为其设置。您可以为整个应用程序全局配置它们:
# config/environments/development.rb
Rails.application.routes.default_url_options[:host] = 'www.mysite.com'
Run Code Online (Sandbox Code Playgroud)
或者在 PDF 模板内的每个助手上单独设置它们:
url.user_url(host: 'www.mysite.com')
Run Code Online (Sandbox Code Playgroud)
希望这能为您带来您所需要的!
归档时间: |
|
查看次数: |
2016 次 |
最近记录: |