在控制器中获取 html erb 模板代码

Get html code of erb template in controller

我有home_controller,里面有[:index, :process_img]个动作。 我需要从动作 :process_img 中获取 :index 动作的全部 html 来源。需要在控制器中访问该代码。

class HomeController < ActionController::Base
  def index
  end

  def process_img
    index_html_code = "the html source of index action should be here"
  end
end

我怎样才能做到这一点?提前致谢!

您可以使用render_to_string(根据与render相同的规则进行渲染,但是returns结果是一个字符串而不是将其作为响应正文发送到浏览器):

render_to_string :index

虽然我认为 render_to_string 是一个惯用的选项,但这里有一种方法可以在普通 ruby 中工作:

ERB.new(File.read "app/views/home/index.html.erb").result binding