在symfony2中的Twig模板中显示JSON数据

时间:2012-04-15 04:46:10

标签: json symfony

我正在尝试在我的应用程序中使用jquery扩展名Event calendar。我首先尝试使用核心php,它工作正常。现在我想在我的symfony2应用程序中使用它,但我无法在我的twig文件中显示它。这是我用于渲染的代码,但我不确定我在哪里做错了。

控制器

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

CollegeStudentBundle_attendance_calendar:
    pattern:  /student/attendance/calendar
    defaults: { _controller: CollegeStudentBundle:StudentAttendance:studentCalendar, _format: json }
    requirements: { _format: (xml|json), _method: GET }  

但是这会显示twig文件的代码。

1 个答案:

答案 0 :(得分:3)

只返回创建的$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;
}

另外我还在假设twig文件是从不同的路径呈现的,而不是CollegeStudentBundle_attendance_calendar路由。