Rails: How to escape ampersand in URL formation
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&:text
In the sample controller it calls the index
method but params[:title]
returns
the value example&: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.
精彩评论