![](/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.