如何在Rails to_json输出中处理HTML实体? [英] How to deal with HTML entities in Rails to_json output?
问题描述
我正在编写一个应用程序,它在后端使用Rails,在前端使用javascript / backbone。我正在尝试将一些rails模型引导到我的javascript 。具体来说,我想将 @courses
的内容加载到名为 window.courses
的js变量中。我在 html.erb
文件中有以下内容。
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 %>
我期待 erb
预处理器将此渲染为有效的javascript,如此
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>
...相反,我得到的代码包括 HTML实体。
... but, instead, I'm getting code that includes HTML entities.
<script type="text/javascript">
//<![CDATA[
window.courses = JSON.parse('[{"code":"myCourseCode", ...
//]]>
</script>
显然,当我尝试解析时,我收到了javascript错误。
Obviously, I get javascript errors when I try to parse this.
有谁知道我是怎么回事可以处理这些HTML实体以生成有效的javascript吗?我意识到一个选项是 unescape客户端的实体,但这似乎是一个迂回的解决方案。有没有办法可以让Rails生成不需要你的JSON nescaping?
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?
推荐答案
如果你打算使用raw(obj.to_json),你必须确保设置了以下内容。
If you intend to use raw(obj.to_json) you MUST ensure the following is set.
ActiveSupport.escape_html_entities_in_json = true
这篇关于如何在Rails to_json输出中处理HTML实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!