[英]How do I use JavaScript to send an email with the Rails 3 Action Mailer?
[英]Action Mailer: How do I render dynamic data in an email body that is stored in the database?
我有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)
它有效,但我不明白這一點,所以我嘗試研究私有方法,並沒有太多的東西讓我擔心這是一個黑客,可能有更好的方法。 建議?
即使你最終無法使用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.
在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
蒂姆的建議正走在正確的道路上。 以下是您在電子郵件操作中實施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屬性中的用戶。 首先,您必須使用<%= user.name %>
來訪問您的使用。 第二個你可以做<%= name %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.