例如,我的对象在php中有DateTime
个对象。
in php
array_push($events,
array(
"date" => new \DateTime('2017-08-01'),
"description" => "This is description of an event"
));
array_push($events,
array(
"date" => new \DateTime('2017-07-19'),
"description" => "Some longer\ntext can also\n be added"
));
像这样解析对象。
in twig
{% for var, value in events %}
var {{var}} = {{ value|json_encode|raw }};
{% endfor %}
output
var 0 = {"date":{"date":"2017-08-01 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Tokyo"},"description":"This is description of an event"};
var 1 = {"date":{"date":"2017-07-19 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Tokyo"},"description":"Some longer\ntext can also\n be added"};
这样text
和boolean
效果很好,但无法将DateTime转换为javascript对象。
有什么好的解决方案吗?
答案 0 :(得分:1)
您应该能够使用JSON中的日期时间字符串来实例化Date
对象,如下所示:
var d = new Date('2017-08-01 00:00:00.000000');
然后可以这样使用,例如:
alert(d.toString()); //Tue Aug 01 2017 00:00:00 GMT+0100 (GMT Summer Time)