在Rails中转义HTML字符串 [英] Unescaping HTML string in Rails

查看:537
本文介绍了在Rails中转义HTML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经继承了以下字符串(我无法对该格式做任何事):

I have the inherited the following string (I can do nothing about the format):

 <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模板中:

I am rendering it in an erb template like this:

<%= the_string %>

目前它呈现为如下文字:

At the moment it renders as text like this:

< iframe class =some_classtype =text / htmlsrc =/ embed / iframe_content.html?id = tsqA5D7_z10width =960height =593marginwidth =0marginheight = 0frameborder =0>< / iframe>

<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"></iframe>

我需要将其呈现为HTML。

I need to render it as HTML.

我尝试过以下操作:


  1. <%= the_string.html_safe%> #呈现字符串不变

  2. <%= CGI.unescapeHTML(the_string)%> #错误类型错误'不能重复NilClass'

  3. <%= CGI.unescapeHTML(the_string).html_safe%> #错误类型错误'不能重复NilClass'

  4. <%= raw the_string%> #呈现字符串不变

  1. <%= the_string.html_safe %> # Renders the string unchanged
  2. <%= CGI.unescapeHTML(the_string) %> # Errors with a Type Error 'can't dup NilClass'
  3. <%= CGI.unescapeHTML(the_string).html_safe %> # Errors with a Type Error 'can't dup NilClass'
  4. <%= raw the_string %> # Renders the string unchanged

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

How can I render this string as HTML?

推荐答案

你似乎已经注意到,有两件事情ou需要照顾:

As you seem to have noticed, there are two things you need to take care of:


  1. 卸载HTML实体

  2. 在您的查看

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

For number 2 <%= raw ... %> should work fine.

对于数字1 CGI.unescapeHTML 是正确的想法,但我不认为它会识别所有HTML实体,因此我建议您查看 HTML Entites宝石

For number 1 CGI.unescapeHTML was the right idea, but I don't think it recognizes all HTML entities so I would recommend taking a look at the HTML Entites gem

您还可以尝试使用 simple_format 帮助方法,但我认为你将要传递一些选项来允许< iframe> 标签

You can also try and use the simple_format helper method, but I think you are going to have to pass it some options for it to allow the <iframe> tag

也强烈建议将您的 unescaping 逻辑转换为辅助方法。

also I would strongly suggest moving your unescaping logic into a helper method.

这篇关于在Rails中转义HTML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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