html - 取消转义 HTML 字符串

标签 html escaping

我继承了以下字符串(我对格式无能为力):

 <iframe \n  class=\"some_class\"\n  type=\"text/html\" \n  src=\"/embed/iframe_content.html?id=tsqA5D7_z10\" \n  width=\"960\" \n  height=\"593\" \n  marginwidth=\"0\" \n  marginheight=\"0\" \n  frameborder=\"0\">\n</iframe>

我在这样的 erb 模板中呈现它:

<%= the_string %>

目前它呈现为这样的文本:

&lt;iframe  class="some_class" type="text/html" src="/embed/iframe_content.html?id=tsqA5D7_z10" width="960" height="593"  marginwidth="0" marginheight="0" frameborder="0"&gt;&lt;/iframe&gt;

我需要将其呈现为 HTML。

我尝试了以下方法:

  1. <%= the_string.html_safe %> # 呈现字符串不变
  2. <%= CGI.unescapeHTML(the_string) %> # 类型错误 'can't dup NilClass' 的错误
  3. <%= CGI.unescapeHTML(the_string).html_safe %> # 类型错误 'can't dup NilClass' 的错误
  4. <%= raw the_string %> # 呈现字符串不变

如何将此字符串呈现为 HTML?

最佳答案

您似乎已经注意到,您需要注意两件事:

  1. 取消转义 HTML 实体
  2. 在您的 View 中打印原始 html

对于数字 2 <%= raw ... %>应该可以正常工作。

对于数字 1 CGI.unescapeHTML是个正确的主意,但我认为它无法识别所有 HTML 实体,因此我建议您查看 HTML Entites gem

您也可以尝试使用 simple_format helper 方法,但我认为您将不得不向它传递一些选项以允许 <iframe>标签

另外,我强烈建议移动您的 unescaping将逻辑转化为辅助方法。

关于html - 取消转义 HTML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10677908/

相关文章:

ruby - 为什么 RegExp.escape 在我的 Ruby 表达式中不起作用?

javascript - 如何使用 javascript 检测文本大小和位置?

javascript - HTML & JS 标记 - 更好的方法可能吗?

.net - 在 String.Format() 中转义单引号

mysql - Ansible 原始和引用

python - 如何以编程方式输入 telnet 的转义字符?

javascript - 在 mousedown 和 mousemove 事件中获取鼠标位置

javascript - 为什么我的 meteor 应用程序创建 "hiddendiv common"div 标签?

ipad - HTML5声音文件播放器

c# - 查询 C# 中表名中的单引号