Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionMailer pass local variables to the erb template

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?

like image 269
Dmitri Avatar asked Sep 07 '12 11:09

Dmitri


1 Answers

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 %>"

like image 197
rap1ds Avatar answered Oct 19 '22 16:10

rap1ds