ActionMailer将局部变量传递给erb模板
我知道我可以定义实例变量,例如:
def user_register(username, email) @username = username @email = email mail(:to => email, :subject => "Welcome!", :template_name => "reg_#{I18n.locale}") end
但是,是否有一种方法可以使用局部变量,就像传递:locals到partials一样?
mail
方法中提供的所有选项均可在http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail中找到。
我们知道render
有一个:locals
选项。 但是我们可以看到没有:locals
选项可用于mail
。 因此,不,没有比使用实例变量更好的方法(除非你想使用像全局变量或持久数据库对象一样可怕的东西 – 不要这样做 )。
实例变量就是您要使用的。
正如ronalchn所指出的那样, render
具有:locals
,而不是mail
方法。 因此,您需要直接访问render
方法才能传递本地。
你可以给mail
一个块,这样就可以访问render
方法,如下所示:
mail(to: "your_mail@example.com", subject: "Test passing locals to view from mailer") do |format| format.html { render locals: { recipient_name: "John D." } } end
现在你应该可以使用"Hello <%= recipient_name %>"
你实际上可以使用locals选项和邮件,它只是有点混乱和如何不一致。
一旦您使用:locals
您就可以使用实例变量在邮件模板中访问这些本地人,例如
:locals => { :name => 'Jane' }
然后在模板中
Dear <%= @name %>,
在Rails 5中,您只需在方法中使用@
定义实例变量。 您无法再为此目的访问locals
属性。
class UserMailer < ApplicationMailer def welcome_email(user_id:, to_email:, user_full_name:, token:) # Mail template variables @user = User.find_by(id: user_id) @token = token mail(:to => to_email, :subject => MAILER_SUBJECTS_WELCOME, :template_path => "user_mailer", :template_name => "welcome_email") end end
然后,您只需使用<%= @user %>
和<%= @token %>
在电子邮件模板中访问它们