April 27, 2012

How capture the default.phtml in a variable inside a controller

Question by Jack

I have a simple question… How could I render the contents of the default.phtml which is in Project/application/layouts/scripts/default.phtml to a variable, so I can have its html.

In the index controller, with an action and a phtml file named test, this would work:

$html = $this->view->render('index/test.phtml');

But, of course, this does not:

$htmlDefaultLayout = $this->view->render('default.phtml');

Since default.phtml is not inside any controller, I guess.

Is there a good way to do that?

Answer by drew010

You can add to the path that Zend_View looks in for views so you could then render the default.phtml file.


// add the layout directory to the path
$this->view->addScriptPath(APPLICATION_PATH . '/layouts/scripts/');

$htmlDefaultLayout = $this->view->render('default.phtml');

The last path added to the scriptPath in Zend_View are the first to be checked (LIFO).

See View Script Paths.

Answer by Starx

You can stop the rendering and grab the output like this:

$this->view->addScriptPath(APPLICATION_PATH . '/layouts/scripts/'); //default layout path
$htmlDefaultLayout = $this->view->render('default.phtml');

Please fill the form - I will response as fast as I can!