如何解析<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=>true, :header=>{:left=>"month,agendaWeek,agendaDay", :center=>"title", :right=>"prev,next"} ...
当我用字符串包装ruby捕获时,我没有收到任何错误:
var options = '<%= @full_calendar_options %>';
但它产生了:
var options = '{:theme=>true, :header=>{:left=>"month,agendaWeek,agendaDay", :center=>"title", :right=>"prev,next"}, ...
这是一个编码的字符串。它不是JSON所以我无法将其解析为对象文字。我试图在JavaScript中获取对象文字。实现这一目标的最佳方法是什么?
答案 0 :(得分:2)
<script>
var options = <%= raw @full_calendar_options.to_json %>;
答案 1 :(得分:0)
您可能希望此输出为JSON,因为您将其分配给JavaScript变量。在那种情况下:
var options = <%= @full_calendar_options.to_json %>