6

I am trying to use the following bit of code to generate a link on my page

%h2= link_to '{{ label }}', product_path('{{ id }}'.html_safe)

This is actually part of a larger HTML block which will serve as a javascript template, and I will later parse using Underscore.js to fill in the {{ id }} and {{ label }} placeholders. So I would like rails to output something to my HTML like

/products/{{ id }}

However, it keeps escaping the spaces and brackeets, and giving me

<a href="/products/%7B%7B%20id%20%7D%7D">{{ label }}</a>

So the url_helper is escaping my string, even though I don't want it to. How can I force it to not do this?

I've tried

%h2= link_to '{{ label }}', product_path('{{ id }}'.html_safe)
%h2= link_to '{{ label }}', product_path(raw '{{ id }}')
%h2= link_to '{{ label }}', raw(product_path('{{ id }}'))

and

%h2=raw( link_to '{{ label }}', product_path('{{ id }}'.html_safe))

But none of them work

EDIT:

Another way to play with this is from rails console,

include ActionController::UrlWriter

ruby-1.9.2-p0 :010 > product_path '{{ id }}'.html_safe
 => "/products/%7B%7B%20id%20%7D%7D" 

Any help appreciated... thanks

Thanks

1
  • It's 2019 and we still face similar problems! Commented Apr 26, 2019 at 17:45

1 Answer 1

8

What about CGI::unescape(product_path('{{ id }}') ? (with the require 'cgi' that goes with it.)

I believe this is Ruby 1.9.2 only but it seems to be the version you're using.

Sign up to request clarification or add additional context in comments.

2 Comments

For the record your solution seems to be ageless since it still works with Ruby 2.6.3 and Rails v5.2.3! Thanks!
Adding a comment to this 10 years old answer of mine as it got a vote recently: If you do this, make sure the unescaped data isn't user-controlled as it could open the door for XSS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.