【问题标题】:Capture HTML output from helper method in Rails从 Rails 中的辅助方法捕获 HTML 输出
【发布时间】:2013-06-23 20:08:08
【问题描述】:

我发现自己试图实现一个不完美的解决方案来不破坏现有代码。

我在 Rails 帮助器类中有一个现有的帮助器方法,它根据参数选择性地呈现几个部分之一:

  def render_widget_container(thingy)
    if thingy.is_awesome?
      render(partial: 'thingies/awesome', locals: {thingy: thingy })
    elsif thingy.sucks?
      render(partial: 'thingies/sucky', locals: {thingy: thingy })
    end
  end

在控制器中,我想从这个帮助程序中捕获输出,并将其作为 JSON 散列中的值之一,如下所示:

@thingy = Thingy.find(params[:id])

respond_to do |format|
  format.json {
    {:name => "thingy 1", :html => render_widget_container(thingy) }
  }
end

我已经尝试了以下结果:

  1. render_widget_container(thingy)

    Render and/or redirect were called multiple times in this action.

  2. capture(render_widget_container(thingy))

    (eval):1: syntax error, unexpected $undefined
    $["<div id=\"video_container\"...
    ^
    (eval):1: syntax error, unexpected ']', expecting $end
    ...r'></div>\n  </div>\n</div>\n"] = ["<DIV ID=\"VIDEO_CONTAINE...
    ...    
    
  3. capture(render_to_string(render_widget_container(thingy)))

    *SHIT TON OF ESCAPED HTML* is not an ActiveModel-compatible object that returns a valid partial path.
    

除了关于为什么要这样做的问题之外,我将如何在我的控制器内从我的助手捕获生成的 HTML?

【问题讨论】:

标签: ruby-on-rails haml partial-views renderpartial


【解决方案1】:

我没有尝试在控制器中捕获渲染输出,而是简单地在视图中捕获渲染动作。不是我最初问题的确切解决方案,但功能齐全。

【讨论】:

    猜你喜欢
    • 2012-12-30
    • 2016-07-22
    • 1970-01-01
    • 2011-03-27
    • 2023-03-03
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多