I'm writing an app that uses Rails on the backend and javascript/backbone on the frontend. I'm trying to bootstrap some rails models into my javascript. Specifically, I'd like to load the contents of @courses
into a js variable called window.courses
. I've got the following in an html.erb
file.
<%= javascript_tag do %>
window.courses = JSON.parse('<%= @courses.to_json %>');
<% end %>
I'm expecting the erb
preprocessor to render this into valid javascript, like so
<script type="text/javascript">
//<![CDATA[
window.courses = JSON.parse('[{"code":"myCourseCode", ...
//]]>
</script>
... but, instead, I'm getting code that includes HTML entities.
<script type="text/javascript">
//<![CDATA[
window.courses = JSON.parse('[{"code":"myCourseCode", ...
//]]>
</script>
Obviously, I get javascript errors when I try to parse this.
Does anyone know how I can deal with these HTML entities in order to produce valid javascript? I realize that one option would be to unescape the entities on the client side, but this seems like a roundabout solution. Is there a way that I can get Rails to produce JSON that doesn't need unescaping?