0

BACKGROUND: I am looking to decode strings that include HTML entities - i.e. "c#" should be converted to "c%23".

I have found the HTMLEntities project to be generally recommended, but have also found what I think is a simpler solution: Using CGI.escape(*string*) or ERB::Util.url_encode(*string*).

QUESTION: Is there any reason why using CGI.escape or ERB::Util.url_encode for this task is a bad idea? If so, how exactly does one implement HTMLEntities in a Rails 3 project - I can't seem to figure it out from the documentation!

4

1 回答 1

1

我不确定每种方法的确切优点。但是,如果您想让 htmlentities 正常工作,您需要将以下内容添加到您的 Gemfile 中:

gem 'htmlentities', :git => "https://github.com/threedaymonk/htmlentities.git"

并运行:

bundle install

然后,在您的控制器中:

class TestController < ApplicationController

  def index 
    coder = HTMLEntities.new
    string = "<élan>" # or whatever string you want to manipulate
    @test = coder.encode(string) # => "&lt;élan&gt;"
  end 
end 

然后用@test 变量做任何你想做的事情——把它写在你的视图页面等上。

于 2012-12-02T18:05:42.243 回答