![](/img/trans.png)
[英]Action Mailer: How do I render dynamic data in an email body that is stored in the database?
[英]how can I replace database value within email body
我通過我的應用程序發送 email。 由於我必須發送不同類型的郵件,我使用數據庫來保存消息,然后獲取 email 正文的消息。
這就是我獲取通知的方式。
def send_share_company(address, cid, from, council_id)
co = Council.find_by(id: council_id)
c = Company.find_by(id: cid)
@a = address.split(',')
@f = from
n = Notification.find_by(id: 'ad4e3718-0689-413b-8a52-96887e0d2aba')
message =n["body"]
from = Email.new(email: 'noreply@my.network', name: "my Network")
subject = + cl["title"] + ' - Event of the Week: ' + c["name"]
to = Email.new(email: a.to_s)
content = Content.new(type: 'text/html', value: message)
mail = Mail.new(from, subject, to, content)
sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
pp sg.client.mail._("send").post(request_body: mail.to_json) unless Rails.env.staging?
end
我將通知正文保存在數據庫中,如下所示。
你好,
#{@f} 認為你應該看看公司#{c["name"]} 。
我想用這些值替換 #{@f} 和 #{c["name"]} 。 但它不會發生。 Email 發送而不替換值。 我該如何解決這個問題。
字符串插值僅發生在字符串文字中。 不在從文件、數據庫或用戶輸入中加載的字符串中——想象一下那會有多危險。
為了擴展插值,您必須引用內容並對其進行評估。 這遠非理想。 一個更好的主意是使用像ERB這樣的模板引擎。
Hello,
<%= #{@f} %> thought you should take a look at the company, <%= #{c["name"]} %>.
require 'erb'
template = ERB.new(n.body)
rendered = template.render(binding)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.