【问题标题】:ActionMailer pass local variables to the erb templateActionMailer 将局部变量传递给 erb 模板
【发布时间】:2012-09-01 06:31:48
【问题描述】:

我知道我可以定义实例变量,例如:

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

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

但是,有没有办法使用 local 变量,就像将 :locals 传递给 partials 一样?

【问题讨论】:

    标签: ruby-on-rails ruby actionmailer erb local-variables


    【解决方案1】:

    mail 方法中可用的所有选项都可以在http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail 找到。

    我们知道render 有一个:locals 选项。但是我们可以看到mail 没有可用的:locals 选项。因此,不,没有比使用实例变量更好的方法了(除非您想使用像全局变量或持久数据库对象这样可怕的东西 - 不要这样做)。

    实例变量是你要使用的。

    【讨论】:

    • 好的。谢谢!那就用吧!
    【解决方案2】:

    可以在邮件中实际使用 locals 选项,只是有点混乱和不一致。

    一旦您使用:locals,您就可以使用实例变量在邮件模板中访问这些本地变量,例如

    :locals => { :name => 'Jane' }
    

    然后在模板中

    Dear <%= @name %>,
    

    【讨论】:

    • 当然!不过,这将在 Rails 2 上进行测试,从那时起可能会发生一些变化。
    • 这在 Rails 4.2 中不起作用。我不希望它基于其他答案。
    • 最好在答案中说明它适用于哪个版本的 Rails。
    【解决方案3】:

    正如 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 &lt;%= recipient_name %&gt;"

    【讨论】:

    • 谢谢@rap1ds,我会尝试这种方法:)
    【解决方案4】:

    在 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
    

    然后您可以使用&lt;%= @user %&gt;&lt;%= @token %&gt; 在您的电子邮件模板中访问它们

    【讨论】:

    • 即使在 Rails 5 之前也是如此。
    猜你喜欢
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2017-11-10
    • 2021-09-06
    相关资源
    最近更新 更多