我有Action Mailer设置,使用我的电子邮件模型的body属性(在数据库中)呈现电子邮件。我希望能够在身体中使用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
更新:有人建议在此主题 http://www.ruby-forum.com/topic/67820 上使用initialize_template_class
。我现在有body
body :msg => initialize_template_class(:user => user).render(:inline => email.body)
它有效,但我不明白这一点,所以我尝试研究私有方法,并没有太多的东西让我担心这是一个黑客,可能有更好的方法。的建议吗
答案 0 :(得分:5)
即使你最终无法使用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.
答案 1 :(得分:5)
在rails 3.2中:内联渲染方法工作正常。
mail(:to => "someemail@address.com",
:subject => "test") do |format|
format.text { render :inline => text_erb_content }
format.html { render :inline => html_erb_content }
end
答案 2 :(得分:2)
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 %>