在symfony2的Twig模板中显示JSON数据 [英] Displaying JSON Data in my Twig template in symfony2
问题描述
我正在尝试在我的应用程序中使用一个jQuery扩展作为事件日历.我先用核心php试过了,效果很好.现在我想在我的symfony2应用程序中使用它,但是我无法在它的树枝文件中显示它.这是我用来渲染的代码,但是我不确定我在哪里做错了.
I am trying to use a jquery extension as Event calendar in my application. I tried it first with core php and it works fine. Now I want to use it in my symfony2 application, but i am not able to display it in my twig file. Here is my code i am using to render but i am not sure where i am doing it incorrect.
public function studentCalendarAction()
{
$year = date('Y');
$month = date('m');
$response = new Response(json_encode(array(
array(
'id' => 111,
'title' => "Event1",
'start' => "$year-$month-10",
'url' => "http://yahoo.com/"
),
)));
$response->headers->set('Content-Type', 'application/json');
return $this->render('CollegeStudentBundle:StudentAttendance:calendar.html.twig',array('response'=>$response));
}
路由器
CollegeStudentBundle_attendance_calendar:
pattern: /student/attendance/calendar
defaults: { _controller: CollegeStudentBundle:StudentAttendance:studentCalendar }
requirements:
_method: GET|POST
TWIG
<script type='text/javascript'>
$(document).ready(function() {
$('#calendar').fullCalendar({
editable: true,
events: "../../student/attendance/calendar",
eventDrop: function(event, delta) {
alert(event.title + ' was moved ' + delta + ' days\n' +
'(should probably update your database)');
},
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
}
});
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
即使我试图像这样使我的Router
Even I tried to make my Router
like this
CollegeStudentBundle_attendance_calendar:
pattern: /student/attendance/calendar
defaults: { _controller: CollegeStudentBundle:StudentAttendance:studentCalendar, _format: json }
requirements: { _format: (xml|json), _method: GET }
但这会显示树枝文件的代码.
But this displays the code of twig file.
推荐答案
只返回创建的$response
,而不是呈现的响应.
Just return the created $response
, not the rendered response.
您的修订版studentCalendarAction
将是
public function studentCalendarAction()
{
$year = date('Y');
$month = date('m');
$jsonData = json_encode(array(
array(
'id' => 111,
'title' => "Event1",
'start' => "$year-$month-10",
'url' => "http://yahoo.com/"
),
));
$headers = array(
'Content-Type' => 'application/json'
);
$response = new Response($jsonData, 200, $headers);
return $response;
}
我还要保证树枝文件是从不同的路径而不是CollegeStudentBundle_attendance_calendar
路径渲染的.
Also I am assmuing that the twig file is rendered from different route, not CollegeStudentBundle_attendance_calendar
route.
这篇关于在symfony2的Twig模板中显示JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!