如何让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
相关产品推荐
相关产品推荐

