Search code examples
phpviewphalcon

It is possible to get Phalcon\Mvc\View rendered output in variable?


I need to give back json object, that has property 'html' with rendered action. Is it possible to do natively with Phalcon vew?

Example:

$posts = NewsPost::find(['limit' => 10]);
$view = new Phalcon\Mvc\View();
$view->setVar('posts', $posts);
$view->setMainView('news/posts'); // not sure if this is correct

// retrieve some data ...
$response = [
    'html' => $view->render(),
    'somedata' => 'somevalues',
    ....
];

P.S. Question regarding phalcon php framework: http://docs.phalconphp.com/en/latest/api/Phalcon_Mvc_View.html


Solution

  • The output buffering needs to be started first:

    $view = new Phalcon\Mvc\View();
    
    $view->setVar('posts', $posts);
    
    $view->start();
    $view->render(); //Pass a controller/action as parameters if required
    $view->finish();
    
    // retrieve some data ...
    $response = [
        'html' => $view->getContent(),
        'somedata' => 'somevalues',
        ....
    ];