开发者

Rails: How to escape ampersand in URL formation

开发者 https://www.devze.com 2023-02-07 02:27 出处:网络
I have a link_to helper like the following: <%= link_to \"example & text\", url_fo开发者_Python百科r(:controller =>\'example\', :title=>\"example & text\") %>

I have a link_to helper like the following:

<%= link_to "example & text", url_fo开发者_Python百科r(:controller =>'example', :title=>"example & text") %>

It frames the URL http://localhost:3000/example?title=example&amp:text

In the sample controller it calls the index method but params[:title] returns the value example&amp:text.

I want to have a value like "example & text". So I have tried CGI::escape() and CGI::escapeHTML() but without luck.


The url needs to be escaped using CGI.escape:

link_to "example & text", :controller => "example", :title => CGI.escape("example & text")

This should generate something like:

<a href="/example?title=example+%26+text">example & text</a>

Then, wherever you're wanting to use this, you can unescape it again to get it back to normal:

CGI.unescape params[:title] # => "example & text"


For this there is a nice rails method called raw.

You can use in this way :

<%= link_to raw("example & text"), url_for(:controller =>'example', :title=>raw("example & text")) %>

One more this & should not be used in the URL as it is used as params separator.

0

精彩评论

暂无评论...
验证码 换一张
取 消