accessing variable in layout

For programming and general questions on Zend Framework
Post Reply
Posts: 23
Joined: Thu Jan 14, 2010 12:45 pm

accessing variable in layout

Post by sephen » Sun Jan 17, 2010 8:42 am


In order to create a variable that you need in your layout you have to set that up in your Bootstrap.
But how do you set up a variable that you can use in your layout when it depends on input from the controller/action?
I've also tried to call the Model_DbTable_ItemsTable via an Class I created 'App_ItemService' but i get an error:
Fatal error: Uncaught exception 'Zend_Db_Table_Exception' with message 'No adapter found for Model_DbTable_ItemsTable'
My Db adapter is set in the application.ini

I can now only get to work when i copy my code in every controller/action but that doesn't seem right.



Posts: 65
Joined: Mon Jan 18, 2010 11:32 am

Re: accessing variable in layout

Post by tomatocms » Tue Jan 19, 2010 6:46 pm

Use plugin to assign the variable value for view.
Assume that you want to attach a CSS style sheet for your site, you should show a variable named APP_URL which represents for website URL.
1) Layout file:

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" xml:lang="en" lang="en">
<link rel="stylesheet" type="text/css" href="<?php echo $this->APP_URL; ?>/skin/default.css" />
<?php echo $this->layout()->content; ?>
2) Create a plugin that initializes all common variables you are going to use in layout:

Code: Select all

class App_Plugin_Init extends Zend_Controller_Plugin_Abstract {
    public function preDispatch(Zend_Controller_Request_Abstract $request) {
		// Get the view instance
		$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
		if (null === $viewRenderer->view) {
		$view = $viewRenderer->view;
		// Assign the variables if you want to use it in layout
		$view->assign('APP_URL', '');
3) Registry Init plugin in your bootstrap:

Code: Select all

$controller = Zend_Controller_Front::getInstance();
$controller->registerPlugin(new App_Plugin_Init());
Above is simple scenario that you can imagine how to access the variables in layout.
If your variables depend on controller/action, tell more details about it. Maybe I can help you.
Nguyen Huu Phuoc, founder of TomatoCMS (based on ZF, jQuery, 960Grid)
Skype: phuoc.69 - Add me on your list if you want to ask/share/discuss about TomatoCMS, Zend Framework

Posts: 15
Joined: Thu Apr 21, 2011 6:19 am

Re: accessing variable in layout

Post by ndefontenay » Wed May 04, 2011 7:20 am


Can you tell me where I should create the plugins?



Posts: 3
Joined: Wed May 04, 2011 10:45 am

Re: accessing variable in layout

Post by mary324 » Wed May 04, 2011 10:50 am


you can install the pluggins in wordpress admin login after installing you have to activate it


Post Reply