我试图用Ruby on Rails中的Line Break替换字符串中的Space,
name = 'john smith'
到目前为止,我已尝试过以下内容:
name.gsub!(" ", "\n")
name.gsub!(" ", "<br>")
name.sub(" ", "\n")
name.sub(" ", "<br>")
但以上都没有奏效。
答案 0 :(得分:3)
将字符串标记为html_safe
时必须小心,特别是如果它可能包含用户输入:
name = 'john smith<script>alert("gotcha")</script>'
name.gsub(' ', '<br>').html_safe
#=> "john<br>smith<script>alert(\"gotcha\")</script>"
Rails会按原样输出该字符串,即包含<script>
标记。
为了利用Rails&#39; HTML转义,您应该只将受信任的部分标记为html_safe
。对于手动连接的字符串:
''.html_safe + 'john' + '<br>'.html_safe + 'smith<script>alert("gotcha")</script>'
#=> "john<br>smith<script>alert("gotcha")</script>"
如您所见,只有<br>
标记保持不变,其余部分已正确转义。
有几个帮助器可用于构建安全字符串以及构建HTML标记。在您的情况下,我会使用safe_join
和tag
:
name = 'john smith<script>alert("gotcha")</script>'
safe_join(name.split(' '), tag(:br))
#=> "john<br />smith<script>alert("gotcha")</script>"
答案 1 :(得分:2)
在html中打印时,您需要使用raw
,否则rails会转义标签
= raw name.gsub(" ", "<br>")
答案 2 :(得分:1)
尝试另一个:
<%= name.gsub(" ", "<br>").html_safe %>
将字符串标记为可信安全。它将被插入到HTML中,而不会执行额外的转义。
"<a>Hello</a>".html_safe
#=> "<a>Hello</a>"
nil.html_safe
#=> NoMethodError: undefined method `html_safe' for nil:NilClass
raw只是html_safe的一个包装器。如果有可能字符串为零,请使用raw。
raw("<a>Hello</a>")
#=> "<a>Hello</a>"
raw(nil)
#=> ""