Unescaping HTML string

大城市里の小女人 提交于 2019-12-01 15:27:48

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

  1. Unescaping the HTML entities
  2. Printing the raw html in your view

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

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

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

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

user1415428

what you are unescaping must not be a string and thats why you are getting Errors with a Type Error can't dup NilClass

Try doing
s = String.new your_obj.to_s

Now do

CGI.unescapeHTML(s)

In the end I had to use the HTMLEntities Gem suggested by Matthew;

  1. Installed the gem with RVM and added it to my Gemfile

  2. Required it in my application.rb

  3. The following was the only way I could get it to render correctly. Note the extra single quotes wrapped around the_string. Without them the angle brackets don't render, though everything else does.

    coder = HTMLEntities.new
    raw coder.decode("'"+the_string+"'")
    

You can try this:

<%= raw the_string %>

Version 3 sounds valuable. Any reason why you are not using the_string?

<%= raw CGI.unescapeHTML(the_string) %>

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!