4

我有 Action Mailer 设置以使用我的电子邮件模型的正文属性(在数据库中)呈现电子邮件。我希望能够在正文中使用 erb,但我不知道如何让它在发送的电子邮件中呈现。

我可以使用此代码将正文作为字符串

# models/user_mailer.rb
def custom_email(user, email_id)
  email = Email.find(email_id)

  recipients    user.email
  from          "Mail It Example <admin@foo.com>"
  subject       "Hello From Mail It"
  sent_on       Time.now

  # pulls the email body and passes a string to the template views/user_mailer/customer_email.text.html.erb
  body          :msg => email.body
end

我遇到了这篇文章http://rails-nutshell.labs.oreilly.com/ch05.html说我可以使用render但我只能render :text上班而不是render :inline

# models/user_mailer.rb
def custom_email(user, email_id)
  email = Email.find(email_id)

  recipients    user.email
  from          "Mail It Example <admin@foo.com>"
  subject       "Hello From Mail It"
  sent_on       Time.now

  # body          :msg => email.body
  body          :msg => (render :text => "Thanks for your order")  # renders text and passes as a variable to the template
  # body          :msg => (render :inline => "We shipped <%= Time.now %>")  # throws a NoMethodError

end

更新:有人推荐initialize_template_class在这个线程上使用http://www.ruby-forum.com/topic/67820。我现在有这个body

body          :msg => initialize_template_class(:user => user).render(:inline => email.body)

它有效,但我不明白这一点,所以我尝试研究私有方法,但那里没有太多东西,这让我担心这是一个黑客,可能有更好的方法。 建议?

4

3 回答 3

6

即使你最终无法使用 render :inline,你也可以自己实例化 ERb。

  require 'erb'

  x = 42
  template = ERB.new <<-EOF
    The value of x is: <%= x %>
  EOF
  puts template.result(binding)

  #binding here is Kernel::binding, the current variable binding, of which x is a part.
于 2010-05-03T19:04:20.887 回答
6

在 rails 3.2 :inline 渲染方法工作得很好。

  mail(:to => "someemail@address.com",
       :subject => "test") do |format|
    format.text { render :inline => text_erb_content }
    format.html { render :inline => html_erb_content }
  end
于 2012-01-29T19:44:32.863 回答
2

蒂姆的建议是正确的。以下是在电子邮件操作中实施 ERB 的方法

def custom_email(user, email_id)
  email = Email.find(email_id)
  # more email setup ...
  body            :msg => ERB.new(email.body).result(binding)
  # or ...
  # body            :msg => ERB.new(email.body).result(user.send(:binding))
end

两个哈希值之间的差异将决定您在数据库表的 body 属性中使用的 erb。使用第一个您必须使用<%= user.name %>才能访问您的使用。用第二个你可以做<%= name %>

于 2010-05-04T22:06:10.823 回答