ActionMailer pass local variables to the erb template

Dmitri picture Dmitri · Sep 7, 2012 · Viewed 10.4k times · Source

I know I could define instance variables e.g:

def user_register(username, email)
  @username = username
  @email = email

  mail(:to => email, :subject => "Welcome!", :template_name => "reg_#{I18n.locale}")
end

But, is there a way to use local variables instead, just like passing :locals to partials?

Answer

rap1ds picture rap1ds · Sep 17, 2014

As ronalchn pointed out, it's the render that has :locals, not the mail method. So, you need a direct access to the render method in order to pass the locals.

You can give a block to the mail and that way gain access to the render method, something like this:

mail(to: "[email protected]", subject: "Test passing locals to view from mailer") do |format|
  format.html {
    render locals: { recipient_name: "John D." }
  }
end

And now you should be able to use "Hello <%= recipient_name %>"