英文:
How to make a text bold in helper.rb ruby file inside a string
问题
我有一个名为schedule_mailer.html.erb的邮件文件
在那个文件中,我尝试使用一个辅助方法,我正在呈现内容
在scheudle_mailer.html.erb中
<p style='font-size:15px;margin:0 25px 20px 25px' >
<%= body_text_tag() %>
</p>
在helper.rb中
我需要发送一个包括<b>
和<br>
的字符串,但我在邮件中接收到的是<b>
和<br>
标签本身。
我的辅助方法
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>
....
....
....
elsif ....
....
end.
因为我尝试在字符串中使用tag(:br),尽管它呈现带有tag(:br)的邮件本身,而不是换行。如何处理字符串中的这种标签以生成HTML?
英文:
i have one mailer file called schedule_mailer.html.erb
in that I'm trying to use a helper method from that I'm rendering the contents
in scheudle_mailer.html.erb
<p style='font-size:15px;margin:0 25px 20px 25px' >
<%= body_text_tag() %>
</p>
in helper.rb
i need to send a string which includes <b>
as well as <br>
but I'm receiving in mail as <b>
and <br>
tag itself.
my helper method
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>
....
....
....
elsif ....
.....
end.
as I have tried tag(:br), inside the string, even though it's rendering the mail with the tag(:br) itself, instead of the break line.
how to approach this kind of tags in the string to HTML?
答案1
得分: 0
这不起作用的原因是,在Rails中,当你将普通字符串附加到一个安全缓冲区时,它会自动转义,以防止跨站脚本攻击。
irb(main):076:0> "<b>Hello".html_safe + "World</b>"
=> "<b>HelloWorld&lt;/b&gt;"
如果你想创建包含HTML标记的文本,你需要标记那些是HTML标记的部分为安全:
"<b>".html_safe + @timings + "</b>".html_safe
不要这样做:
"<b>#{ @timings }</b>".html_safe
除非你确切知道内容是安全的,不包含用户输入。
这就是标记助手自动为你执行的操作:
content_tag(:b, @timings)
tag.b(@timings)
但这段代码很可能实际上不应该放在助手中。使用视图或部分并在ERB中编写它。
英文:
The reason this doesn't work is that in Rails when you append a normal string to a safe buffer its automatically escaped to prevent XSS attacks.
irb(main):076:0> "<b>Hello".html_safe + "World</b>"
=> "<b>HelloWorld&lt;/b&gt;"
If you want to create text that contains HTML tags from a helper you need to mark the portions that are HTML tags as safe:
"<b>".html_safe + @timings + "</b>".html_safe
Do not do:
"<b>#{ @timings }</b>".html_safe
Unless you actually know that the content is actually safe and doesn't contain user input.
This is what the tag helpers do automatically for you:
content_tag(:b, @timings)
tag.b(@timings)
But this code most likely doesn't actually belong in a helper in the first place. Use a view or a partial and write it in ERB.
答案2
得分: -2
其中一个我尝试过且对我有效的解决方案是在邮件中使用html_safe
,如下:
<%= body_text_tag().html_safe %>
英文:
one of the solutions which I tried and worked for me is to use html_safe, in the mailer.
as
<%= body_text_tag().html_safe %>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论