Wednesday, October 10, 2007

escape_javascript goodness

I was trying to print some javascript in application .rhtml and wanted to use a link_to helper to print a link.
var user = <%= current_user.json_user_data %>;
$('welcome_p').innerHTML = "Welcome " + user.login + '! ( <%= link_to("Sign out", session_path(), :method => :delete, :class => "wlcmLnk")) -%> )';
This resulted in an error as link_to expanded to
$('welcome_p').innerHTML = "Welcome " + ud.login + '! ( <a href="/session" class="wlcmLnk" onclick="var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);f.submit();return false;">Sign out</a> )';

The single quotes are not escaped :(

But not to worry. escape_javascript will do the needful. It escapes carrier returns and single and double quotes.
$('welcome_p').innerHTML = "Welcome " + ud.login + '! ( <a href=\"/session\" class=\"wlcmLnk\" onclick=\"var f = document.createElement(\'form\'); f.style.display = \'none\'; this.parentNode.appendChild(f); f.method = \'POST\'; f.action = this.href;var m = document.createElement(\'input\'); m.setAttribute(\'type\', \'hidden\'); m.setAttribute(\'name\', \'_method\'); m.setAttribute(\'value\', \'delete\'); f.appendChild(m);f.submit();return false;\">Sign out</a> )';

Njoy!

No comments: