当在 Slim PHP 微框架的模板中调用 json_encode 时,"flash":{} 被添加到我的 json 输出中

"flash":{} is added to my json output when json_encode is called inside the template of Slim PHP microframeork

我正在尝试从 Mongodb 集合中读取一些数据,return 结果留给我 API。从我的用户集合中查询所有文档后,我将结果数组发送到我的模板(此处为 Slim 微框架),最后调用 json_encode() 发送创建响应。这是我的代码:

<?php

require 'vendor/autoload.php';

//instancia o objeto Slim
$app = new \Slim\Slim(array(
    'templates.path' => 'templates'));

//List users
$app->get('/', function () use ($app) {
    $mongo = new MongoClient('mongodb://user:pass@localhost:27017');
    $db = $mongo->mydatabase;
    $col = $db->users;
    $cursor = $col->find();
    $data = iterator_to_array($cursor, true);
    $app->render('default.php', $data, 200);
});

//run Slim
$app->run();

?>

模板dafault.php:

<?php 
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);
?>

如果我在模板外调用 echo json_encode($newa),一切正常。

输出为:

{
flash: {}
54b71d4e097a4dcd4bf49684: {...}-
54bc5bd5cdce605e70325c4e: {...}-
}

谁能告诉我这个 "flash: {}" 是从哪里来的?我怎样才能让它消失?! 谢谢。

Slim 为 Flash Messaging in your rendered output. You could disable the Flash middleware, but I expect you actually want to use a Response object 添加了 flash 变量,而不是渲染视图:

<?php
    $app->get('/', function () use ($app) {
        $mongo = new MongoClient('mongodb://user:pass@localhost:27017');
        $db = $mongo->mydatabase;
        $col = $db->users;
        $cursor = $col->find();
        $data = iterator_to_array($cursor, true);
        $app->response->headers->set('Content-Type', 'application/json; charset=utf-8')

        // print or echo output will be appended to Response
        echo json_encode($data);

        // Alternatively, explicitly set the Response body:
        // $app->response->setBody(json_encode($data));
    });
?>