render_to_string

Posted by jeff Wed, 26 Mar 2008 12:28:00 GMT

Rendering a view in Rails to a String

This is old hat for pros, but this is such a useful method that I wanted to bring it up for anyone googling for this functionality (as I was months back).

Occasionally you'll want to render something in rails and keep the result in a string (to save into a db or file or to display later) rather than displaying it immediately. If you try to make a call to render and then go about your business redirecting or displaying another view you'll get a wonderful ActionController::DoubleRenderError telling you "Can only render or redirect once per action". You want to use render_to_string.

Example: rendering a haml template that has been loaded into template_content

rendered_result = render_to_string( :inline => template_content,
  :type => :haml,
  :locals => { :blah => @blah }
)

Comments

Leave a comment

Comments