Ruby on Rails:如何将字符串呈现为HTML? [英] Ruby on Rails: how to render a string as HTML?

查看:378
本文介绍了Ruby on Rails:如何将字符串呈现为HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

  @str =< b>嗨< / b> 

在我的erb视图中:

 <%= @str%> 

页面上显示的内容是:< b> Hi< b> 当我真正想要的是 Hi 。什么是解释字符串为HTML标记的红宝石方式?






编辑

  @str =< span class = \classname \> hello< / span> 

如果在我看来我是这样做的

 <%raw @str%> 

HTML源代码是< span class = \classname \\ >> hello< / span >我真正想要的是< span class =classname> hello< / span> (没有反斜杠是逃避双引号)。什么是unes​​cape这些双引号的最好方法?

解决方案

UPDATE



出于安全原因,建议使用 sanitize 而不是 html_safe 链接



现在发生的事情是,作为一项安全措施,Rails正在为您转义您的字符串,因为它可能嵌入了恶意代码。但是如果你告诉Rails你的字符串是 html_safe ,它就会通过它。

  @str =< b>嗨< / b>。html_safe 
<%= @str%>

OR

  @str =< b>嗨< / b> 
<%= @ str.html_safe%>

使用 raw 可以正常工作,但所有正在将字符串转换为字符串,然后调用html_safe。当我知道我有一个字符串时,我更喜欢直接调用html_safe,因为它跳过了一个不必要的步骤,并且使得它更清楚发生了什么。有关字符串转义和XSS保护的详细信息位于此Asciicast 中。

I have

@str = "<b>Hi</b>"

and in my erb view:

<%= @str %>

What will display on the page is: <b>Hi</b> when what I really want is Hi. What's the ruby way to "interpret" a string as HTML markup?


Edit: the case where

@str = "<span class=\"classname\">hello</span>"

If in my view I do

<%raw @str %>

The HTML source code is <span class=\"classname\">hello</span> where what I really want is <span class="classname">hello</span> (without the backslashes that were escaping the double quotes). What's the best way to "unescape" those double quotes?

解决方案

UPDATE

For security reason, it is recommended to use sanitize instead of html_safe. Link


What's happening is that, as a security measure, Rails is escaping your string for you because it might have malicious code embedded in it. But if you tell Rails that your string is html_safe, it'll pass it right through.

@str = "<b>Hi</b>".html_safe
<%= @str %>

OR

@str = "<b>Hi</b>"
<%= @str.html_safe %>

Using raw works fine, but all it's doing is converting the string to a string, and then calling html_safe. When I know I have a string, I prefer calling html_safe directly, because it skips an unnecessary step and makes it clearer what's going on. Details about string-escaping and XSS protection are in this Asciicast.

这篇关于Ruby on Rails:如何将字符串呈现为HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆