Inline ERB templating — for free

I needed to support an email templating system in the project I'm working on, but creating my own seemed like a pain, especially with so many templating systems out there. I looked at Liquid (the templating system used by Mephisto) and eRuby, but ultimately, the answer was right under my nose the entire time…

Rails makes powerful use of its render method to make sure almost anything you throw at the framework will be output correctly. But while developing my email templating system, I realized what I really needed was the ability to render the contents of a template I had stored in my database to a string, and display the results in a section of my page, through RJS output.

Although sparsely documented, render_to_string makes this task beyond simple. This method takes arguments similar to those you would pass to render, but instead of forcing the output through your view, you get it in variable to do with it as you please. Here is an example of the render_to_string method in action:

class Email < ApplicationController
  def merge_with_template
    @email = Email.find(params[:id])
    # Our template uses a @user variable, so we need to declare it here
    @user = @email.user

    @email_template = EmailTemplate.find(params[:email_template_id])
    email_with_template = render_to_string(:inline => @email_template.body)

    render :update { |p| p.replace_html('email_body', email_with_template) }
  end
end

Our template looks like this:

Hello, <%= h @user.fullname %>

Thank you for your interest in <%= h @user.product.name %>. We will be
shipping your item to you within the next 2 business days through
<%= h @user.shipping_method.name %>.

Sincerely,
Sales Team

With our template and our controller code in place, all we need to do is call our action through an AJAX request and we will get the populated content back in our email body, so we can muck around with it if necessary (adding personal touches, etc).

Leave a Reply