2017-04-12 52 views
1

如何在我的index.html.erb文件中解析<script>标记中的红宝石散列?在index.html.erb文件的脚本标记中解析ruby散列

控制器:

@full_calendar_options = { theme: true, header: { left: 'month,agendaWeek,agendaDay', center: 'title', right: 'prev,next' }, defaultView: 'agendaWeek', buttonIcons: { prev: 'calendar-left-arrow', next: 'calendar-right-arrow' } } 

在index.html.erb,这将产生JavaScript语法错误:

<script> 
var options = <%= @full_calendar_options %>; 

,因为它会产生:

var options = {:theme=&gt;true, :header=&gt;{:left=&gt;&quot;month,agendaWeek,agendaDay&quot;, :center=&gt;&quot;title&quot;, :right=&gt;&quot;prev,next&quot;} ... 

当我用一个字符串包装红宝石捕获,我得到没有错误:

var options = '<%= @full_calendar_options %>'; 

但是它产生:

var options = '{:theme=&gt;true, :header=&gt;{:left=&gt;&quot;month,agendaWeek,agendaDay&quot;, :center=&gt;&quot;title&quot;, :right=&gt;&quot;prev,next&quot;}, ... 

这是一个编码的字符串。它不是JSON,所以我不能将它解析为对象字面值。我试图在JavaScript中获取对象字面值。达到此目的的最佳方法是什么?

回答

0

您可能希望将此输出转换为JSON,因为它看起来像将它分配给JavaScript变量。在这种情况下:

var options = <%= @full_calendar_options.to_json %> 
+0

我为什么一定要用检查吗?为什么不会to_json正常工作? – Donato

+0

糟糕,你是对的。 'to_json'可以在没有'inspect'的情况下正常工作。 –

+1

我认为html_safe可能也需要:@ full_calendar_options.to_json.html_safe – Donato

1
<script> 
var options = <%= raw @full_calendar_options.to_json %>; 
+0

出于好奇,为什么Rails默认会跳过这些数据?这不是一个不便吗?谁会希望看起来像这样的数据? {:theme = > true,:header = > – Donato

+0

这是一个很好的解释:http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/基本上,因为<%= %>内的任何内容都可以不安全的用户输入,包括恶意的JavaScript,所以默认情况下会将其转义以免造成恶意。 – Donato