【问题标题】:Rails render_to_stringRails render_to_string
【发布时间】:2017-03-22 06:56:09
【问题描述】:

我在使用 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 文件。

非常感谢

【问题讨论】:

  • 引用,栈溢出问题。您是否尝试只传递 reservations/print 而没有模板关键字?
  • 我认为--api 标志不是问题所在。根据 Rails Api 上的文档,AbstractController::Rendering 是默认的,此模块包含 render_to_string 方法。
  • 嗨,丹,感谢您抽出宝贵时间回答。我有这个,还有一些。我会更新问题。
  • 抱歉再添加一条评论,如果可能的话,只是想要一些新鲜的眼睛

标签: ruby-on-rails render-to-string


【解决方案1】:

虽然我不认为这是执行以下工作的最佳解决方案。

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 中。

【讨论】:

  • 这应该不再需要(但我还没有测试过)。请参阅模块 ActionController::Renderers::ClassMethods:“ActionController::Base 和 ActionController::API 都包含 ActionController::Renderers::All,使控制器中的所有渲染器都可用。”
【解决方案2】:

你可以在你的行动中做这样的事情:

     respond_to do |format|
       format.html { render layout: 'your_layout' } # this is for your html responses if you need to respond with html
       format.json { # this block will execute for your json requests

        html = render_to_string action: :index, layout: false, :formats => [:html]
        render json: {data: html}
     }

【讨论】:

    【解决方案3】:

    试试下面的 sn-p 代码:

    ActionController::Base.new.render_to_string("mailer/your-html-file", locals: { data: your-json-data-that-you-wanna-add-to-your-html-file })
    

    【讨论】:

      【解决方案4】:

      这是适合我的解决方案:

      render_to_string partial: 'participant_data.html.erb'
      

      文件必须这样命名:

      tickets/_participant_data.html.erb
      

      【讨论】:

        猜你喜欢
        • 2011-08-27
        • 2022-06-16
        • 1970-01-01
        • 2011-12-03
        • 2017-03-28
        • 2011-09-18
        • 2017-11-12
        • 1970-01-01
        • 2011-10-28
        相关资源
        最近更新 更多