【问题标题】:How do I output a json dates array with RABL如何使用 RABL 输出 json 日期数组
【发布时间】:2015-11-23 14:21:53
【问题描述】:

我正在尝试使用 chronoline.js 时间线在我的 Rails 应用程序中显示事件。 chronoline 期望的格式是:

var events = [
{dates: [new Date(2015, 1, 29)], title: "First Event"},
{dates: [new Date(2015, 3, 9), new Date(2015, 3, 11)], title: "Second Event"}
]; 

日期节点是一个包含一个或两个日期的数组,具体取决于事件是否跨越多天。 我正在尝试使用 RABL 或 JBuilder 生成它,但我不明白如何创建数组或附加“新日期”。

我是新手。我最终尝试在 RABL 视图中将它们全部连接起来:

collection @events

attributes :title

node :dates do |d|
if d.end.nil? then
   "[new Date(" + d.start.to_s + ")]"
 else
   "[new Date(" + d.start.to_s + "), new Date(" + d.end.to_s + ")]"
  end
end

....但这不起作用,因为它将整个数组语句输出为引号中的字符串。但是这样做总感觉不对。

如何让 RABL(或 JBuilder)组装阵列?

【问题讨论】:

  • 我已经编辑了我的答案几次,试图完善它。让我知道它是否适合您!

标签: ruby-on-rails json rabl


【解决方案1】:

您无法在来自 Rabl 或 jBuilder 的 JSON 响应中实现这一点,因为 Chronoline 需要 JavaScript 日期对象。

为此,我建议如下:

1) 将所需的 json 加载到数据属性中的视图中:

<%= content_tag :div, "", id: "mytimeline", data: { events: timeline_json(@events) } %>

2) 使用辅助方法来构造 JSON,日期格式可以很容易地用 MomentJS 解析:

def timeline_json(events)
  events.map { |event| { start: event.start.strftime("%F %T"), end: event.end.strftime("%F %T"), title: event.title } }.to_json
end

3) 安装 momentjs-rails gem,并确保它已加载到您的资产管道中。我们将使用它来解析 JSON 日期,以便轻松地将它们转换为 Javascript 日期对象。

4) 在 JavaScript 中使用 map,在实例化 Chronoline 时重铸日期对象。

function drawChronoline() {

  // Load the Raw JSON data:
  var raw_data = $("#mytimeline").data('events');

  // Loop over the JSON, and map it into the format required by Chronoline. Here's a simple example to get you started:
  var events = raw_data.map(function(event){
    return { dates: [moment(event.start).toDate(), (!event.end ? null : moment(event.end).toDate())], title: event.title }
  });

  // Instantiate chronoline, with your mapped data:
  var timeline = new Chronoline($("#mytimeline"), events);
}

如果您更喜欢使用 RABL 加载事件的异步方法(而不是使用 Helper 和 Data-attribute),您可以通过以下方式轻松实现:

var raw_data = $.get("/events.json");

你的 RABL 看起来就像:

collection @events

attributes :title

node(:start) { |event| event.start.strftime("%F %T") }
node(:end) { |event| event.end ? event.end.strftime("%F %T") : "" }

【讨论】:

  • 非常感谢 riarcombe。效果很好。一旦我在实例化 Chronoline 时将 $("#mytimeline") 更改为我的元素 ID,我得到了正确的结果。您的建议非常明确,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
相关资源
最近更新 更多