Rails 视图助手似乎不适用于 render_to_string [英] Rails views helper don't seems to work with render_to_string
问题描述
我尝试使用 gem wicked_pdf 将 rails 视图转换为 pdf.但是当我做这样的 render_to_string 时
I try to convert rails views into pdf with the gem wicked_pdf. But when I do a render_to_string like this
ActionController::Base.new.render_to_string(template: "templates/pdf_meteo.html.erb", locals: {communaute_meteo_id: id}, layout: 'pdf')
user_path
之类的方法不起作用并返回未定义的方法错误...(请注意,如果我在 html 中呈现页面,则该页面可以正常工作)如果有人可以帮助我!
Methods like user_path
don't work and return undefined method error... (note that the page work properly if I render it in html)
If someone can help me !
推荐答案
遗憾的是,使用 render_to_string
将无法访问 Rails URL 帮助程序.一种解决方法是使用类似 url: Rails.application.routes.url_helpers
:
Unfortunately, using render_to_string
will not give you access to Rails URL helpers. One workaround is to include them directly in the locals
that you pass into the PDF template using something like 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'
)
然后在您的 PDF 模板中,您可以使用以下命令调用它们:
And then inside of your PDF template you would call them with:
url.user_path
请记住,默认情况下 _path
URL 助手将是相对,而不是绝对路径.您可以改为使用帮助程序的 _url
版本,并以几种不同的方式为它们设置 host
.您可以为整个应用全局配置它们:
Keep in mind that by default the _path
URL helpers will be relative, and not absolute paths. You can instead use the _url
version of the helpers and set the host
for them in a few different ways. You can configure them globally for your entire app:
# config/environments/development.rb
Rails.application.routes.default_url_options[:host] = 'www.mysite.com'
或在您的 PDF 模板内的每个助手上单独设置它们:
or set them individually on each helper inside of your PDF template:
url.user_url(host: 'www.mysite.com')
希望能满足您的需求!
这篇关于Rails 视图助手似乎不适用于 render_to_string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!