我在使用 rails render_to_string 函数时遇到了困难。我已经使用 --api 标志创建了一个应用程序,所以我认为这可能是问题,因为我已经在“完整”rails 应用程序中进行了测试,并且它的工作正常。
基本上我在打电话:
body_html = render_to_string(template: 'reservations/print')
我也试过
body_html = render_to_string('reservations/print')
body_html = render_to_string(partial: 'reservations/print')
body_html = render_to_string(partial: 'reservations/print.html.erb')
它应该返回该模板的 html。文件名是 print.html.erb 并且只有基本数据,即
<p> Hello world. </p>
当我输出 body_html 它是空的。
我引用了这个 SO 问题 What is the correct way to render_to_string in wicked pdf?我还将使用 Wicked PDF 生成 pdf 文件。
非常感谢
最佳答案
虽然我不认为这是执行以下工作的最佳解决方案。
ac = ActionController::Base.new()
html_string = ac.render_to_string :template => 'path_to_file' e.g. 'post/show'
Rails API 模式下的Application Controller 文件继承自ActionController::API,所以我猜想渲染的功能在ActionController::Base 中。
关于ruby-on-rails - Rails render_to_string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40490463/