You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Rails邮件助手helper.rb中的HTML标签在邮件中正确渲染

解决邮件模板中HTML标签无法渲染的问题

问题根源是Rails默认会对ERB输出的字符串进行HTML转义,导致你的<b>、<br>等标签被转成实体字符,直接显示文本而非渲染格式。以下是几种可行的解决办法:

方法1:在Helper方法中标记字符串为安全

在helper返回的HTML字符串末尾调用html_safe方法,明确告诉Rails该字符串无需转义:

def body_text_tag()
  body = "This email to inform you that"
  if @creation
    body +  "your hotel schedule has been created <br>
      <b>timings :</b>  #{@timings}, <br>
      <b>Room number :</b> #{@room_number},<br>
      ....".html_safe
  elsif 
    # 其他分支逻辑
  end
end

方法2:在模板中使用raw方法强制不转义

在ERB模板里,用raw包裹helper的调用,跳过转义步骤:

<p style='font-size:15px;margin:0 25px 20px 25px' >  
  <%= raw body_text_tag() %>
</p>

方法3:正确使用Rails的tag方法构建HTML

你之前尝试的tag(:br)无效,是因为将它拼接到普通字符串后,整个字符串丢失了安全标记。正确的做法是用tag方法构建各部分HTML,再拼接:

def body_text_tag()
  body = "This email to inform you that"
  if @creation
    body += "your hotel schedule has been created #{tag(:br)}"
    body += "#{tag.b('timings :')} #{@timings}, #{tag(:br)}"
    body += "#{tag.b('Room number :')} #{@room_number}, #{tag(:br)}...."
    body
  elsif 
    # 其他分支逻辑
  end
end

(注:用tag方法生成的HTML本身就是安全的,无需额外调用html_safe)

内容的提问来源于stack exchange,提问作者jansha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 02:45:10