我知道我可以定义实例变量,例如:
def user_register(username, email)
@username = username
@email = email
mail(:to => email, :subject => "Welcome!", :template_name => "reg_#{I18n.locale}")
end
但是,是否有一种方法可以使用本地变量,就像将:locals传递给partials一样?
我知道我可以定义实例变量,例如:
def user_register(username, email)
@username = username
@email = email
mail(:to => email, :subject => "Welcome!", :template_name => "reg_#{I18n.locale}")
end
但是,是否有一种方法可以使用本地变量,就像将:locals传递给partials一样?
:locals
的是render
而不是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
属性来达到此目的。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 %>
即可访问它们。
你实际上可以在邮件中使用locals选项,只是有点混乱和不一致。
一旦你使用了:locals
,你就可以在邮件模板中通过实例变量访问这些locals,例如:
:locals => { :name => 'Jane' }
然后在模板中
Dear <%= @name %>,