ruby-on-rails – 如何将erb模板渲染为字符串内部动作?

我需要一串html(类似“< html>< body> Hello World< / body>< / html>”)来传真.

我把它写成了一个单独的erb文件:views / orders / _fax.html.erb,
并尝试渲染erb:html_data = render(:partial =>’fax’).

以下是引发问题的控制器的一部分:

respond_to do |format|
      if @order.save   
        html_data = render(:partial => 'fax')
        response = fax_machine.send_fax(html_data)
        ......

        format.html { redirect_to @order,notice: 'Order was successfully created.' }
        format.json { render json: @order,status: :created,location: @order }
      else  
        format.html { render action: "new" }
        format.json { render json: @order.errors,status: :unprocessable_entity }
      end
    end

它给了我一个AbstractController :: DoubleRenderError如下:

AbstractController::DoubleRenderError in OrdersController#create

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect,and at most once per action. Also note that neither redirect nor render terminate execution of the action,so if you want to exit an action after redirecting,you need to do something like "redirect_to(...) and return".

如何解决这个问题呢?

解决方法

如果您只需要渲染的HTML,并且不需要控制器中的任何功能,您可以尝试直接在辅助类中使用ERB,例如:
module FaxHelper

  def to_fax
    html = File.open(path_to_template).read
    template = ERB.new(html)
    template.result
  end

end

ERB docs更详细地解释了这一点.

编辑

要从控制器获取实例变量,请将绑定传递给结果调用,例如:

# controller
to_fax(binding)

# helper class
def to_fax(controller_binding)
  html = File.open(path_to_template).read
  template = ERB.new(html)
  template.result(controller_binding)
end

注意:我从来没有这样做过,但似乎可行:)

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...