How to render erb template to string inside action?

前端 未结 4 1702
囚心锁ツ
囚心锁ツ 2020-12-16 14:52

I need a string of html (something like \"Hello World\") for faxing purpose.

I wrote it into a seprat

相关标签:
4条回答
  • 2020-12-16 15:22

    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

    0 讨论(0)
  • 2020-12-16 15:34

    If you don't want to escape html, just call .html_safe on it:

    "<html><body>Hello World</body></html>".html_safe

    Re your error, please post your OrdersController - looks like you are calling render or redirect more than once in the create action.

    (Btw, just in case you are trying it - you can't render a partial in a controller - you can only render partials in views)

    Edit: yeah your problem is you trying to render a partial in the controller action. You could use an after_create callback to set up and send the fax - though again you won't want to use a partial (as they are for views). http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

    Edit: for your fax problem,you could create a normal Ruby Class, see this excellent bit of advice from Yehuda: https://stackoverflow.com/a/1071510/468009

    0 讨论(0)
  • 2020-12-16 15:41

    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 :)

    0 讨论(0)
  • 2020-12-16 15:43

    The reason is you cannot render or redirect inside the same action more than once at a given time.

    But in your code, you have both render and redirect. I think in your controller you can use simply only the render, assuming you don't need any json output.

    Try this

    def create
      @order.save   
      render(:partial => 'fax')
    end
    

    I haven't tested this, but I guess you get the idea :), and think about a way to handle errors as well (in case order didn't save).

    0 讨论(0)
提交回复
热议问题