Rendering Rails Template as String


This is a nice trick that is useful, for example if you need to send an html string via an api endpoint.
Instead of constructing the string manually like this:

# api controller
@title = "some title"
@html_string ="<h1>#{@title}</h1>"

You can put the template into a template file, for example ‘html_string.erb’, and call ‘render_to_string’

# html_string.erb
<h1><%= @title %></h1>
# api controller
@html_string = render_to_string(:html_string)

This is especially useful if the html string is dynamic and complicated, as you can use partials.