Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render erb template to string inside action?

I need a string of html (something like "<html><body>Hello World</body></html>") for faxing purpose.

I wrote it into a seprate erb file: views/orders/_fax.html.erb , and try to render the erb in action: html_data = render(:partial => 'fax').

Here is part of the controller that raises the issue:

  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

It gave me an AbstractController::DoubleRenderError as below:

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".

How to solve this problem?

like image 914
Feng Wan Avatar asked Jan 16 '13 02:01

Feng Wan


2 Answers

If you only need the rendered HTML, and don't need any functionality from the controller, you might try using ERB directly within a helper class, eg.:

module FaxHelper

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

end

The ERB docs explain this in more detail.

EDIT

To get the instance variables from the controller, pass the binding into the result call, eg:

# 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

Note: I've never done this, but it seems workable :)

like image 111
zetetic Avatar answered Sep 20 '22 20:09

zetetic


Use the #render_to_string method

it works the same way as the typical render method but useful when you need to add some templated HTML to a json response

http://apidock.com/rails/ActionController/Base/render_to_string

like image 44
George Taveras Avatar answered Sep 24 '22 20:09

George Taveras