如何在Rails应用表单文本域中渲染模型参数
解决Rails自定义邮件模板变量渲染问题
为什么当前代码不生效
你当前的@email.template.body是存储的字符串,Rails不会自动解析其中的ERB标签(<%= @goal.title %>),只会原样输出,所以才会显示代码而非实际值。
两种可行解决方案
方案一:用ERB动态解析模板(适合技术用户自定义)
通过Ruby的ERB类手动解析模板内容,将变量替换为实际值:
- 在控制器或辅助方法中添加渲染逻辑:
# app/helpers/email_helper.rb module EmailHelper def render_erb_template(template, context) # 限制上下文变量范围,降低安全风险 allowed_vars = { goal: context.instance_variable_get(:@goal), contact: context.instance_variable_get(:@contact) } ERB.new(template).result(binding) end end
- 在视图中调用辅助方法生成mailto链接:
<% rendered_body = render_erb_template(@email.template.body, self) %> <% subject = "#{@tracker.title} #{@email.template.subject}" %> <% body_content = "Hey #{@contact.first_name},\n\n#{rendered_body}\n\nThanks, Cat" %> <a href="mailto:<%= @contact.email_address %>?subject=<%= URI.encode_www_form_component(subject) %>&Body=<%= URI.encode_www_form_component(body_content) %>">Send template</a>
注意:如果模板由普通用户输入,此方法存在代码注入风险,建议严格限制可使用的变量,或改用更安全的占位符方案。
方案二:使用占位符替换(安全且易操作)
放弃ERB标签,改用自定义占位符(比如{{goal_title}}),通过字符串替换实现变量渲染:
- 让用户在模板文本域中使用占位符:
We'd love to run a feature on {{goal_title}} for our magazine.
- 在视图中替换占位符:
<% replaced_body = @email.template.body .gsub("{{goal_title}}", @goal.title) .gsub("{{contact_name}}", @contact.first_name) %> <% subject = "#{@tracker.title} #{@email.template.subject}" %> <% body_content = "Hey #{@contact.first_name},\n\n#{replaced_body}\n\nThanks, Cat" %> <a href="mailto:<%= @contact.email_address %>?subject=<%= URI.encode_www_form_component(subject) %>&Body=<%= URI.encode_www_form_component(body_content) %>">Send template</a>
这种方法完全避免代码执行风险,适合非技术用户创建模板,你可以在表单旁列出所有可用占位符,方便用户参考。
编辑器推荐
不需要特殊代码编辑器,普通文本输入域即可满足需求。若要提升用户体验:
- 在表单下方标注所有可用占位符(如
{{goal_title}}、{{contact_name}}等) - 使用Rails自带的Trix富文本编辑器,支持基本格式排版且不影响占位符替换
- 添加简单按钮,让用户点击即可插入对应占位符,减少手动输入错误
内容的提问来源于stack exchange,提问作者Cat Morley
相关产品推荐
相关产品推荐

