11.29.07

Use escape_javascript when rendering model data into a js string

Posted in Ruby, rails at 5:00 am by Robert Horvick

To give users a better view into some data I want to render local points of interest with current deals onto a Google map.  In the marker popup I’d like the user to be able to drill down further into the details.  To do this I want a hyperlink to the deal details.

 The link_to I want is:

link_to "Details", { :controller => "deal", :action => "details", :id => deal.id }

link_to rendering link in javascript

 The problem is that the rendered <a> should go into a blob of javascript such as:

       GEvent.addListener(        marker,"click",        function() {    

          var myHtml = "<b><%= h deal.Restaurant.name %></b><br/><%= h deal.description %></br><%= link_to "Details", { :controller => "deal", :action => "details", :id => deal.id } %>";    

          map.openInfoWindowHtml(marker.getLatLng(), myHtml);    

        }    

      );

That fails because the string literal has embedded double quotes.

Since ‘h’ (alias for html_escape) exists I figured there had to be a javascript version as well - and action view did not disappoint.

The updated code is:

      GEvent.addListener(        marker,"click",        function() {    

          var myHtml = "<b><%= escape_javascript h(deal.Restaurant.name) %></b><br/><%= escape_javascript h(deal.description) %></br><%= escape_javascript link_to("Details", { :controller => "deal", :action => "details", :id => deal.id }) %>";    

          map.openInfoWindowHtml(marker.getLatLng(), myHtml);    

        }    

      );

The javascript now renders correctly and the link to the details page functions as expected.

I’m still shooting in the dark - but I think I’m facing the target.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Leave a Comment