Search code examples
jsonzend-frameworkzend-view

How to use rendered Zend View in JSON Object


I'm trying to use a rendered view in a JSON object and then return this to the client. How can I render a phtml file that doesn't really belong to specific action?

The requested action from the client has no view. It then calls prepareForm(). Inside this function i want to render form.phtml and pass the output to the 'html' key of the array.

private function prepareForm()
    {
        $json = Zend_Json::encode(array(
            'html' => $this->partial('form.phtml'),
            'role' => $this->role,
            'lang' => $this->lang
        ));

        echo $json;
    }

How can I do this in the Zend Framework? What's the best way to do this?

Many thanks


Solution

  • You need an Zend View instance:

    private function prepareForm()
    {
        $view = new Zend_View();
        $path = '/../'; // Replace with path to phtml
    
        $view->addScriptPath($path);
    
        $json = Zend_Json::encode(array(
            'html' => $view->render('form.phtml'),
            'role' => $this->role,
            'lang' => $this->lang
        ));
    
        echo $json;
    }