In each module in my application I'll have a main content section and a sidebar menu.
In my layout I have the following...
<div id="main" class="span8 listings">
<?php echo $this->content; ?>
</div>
<div id="sidebar" class="span4">
<?php echo $this->sidebar; ?>
</div>
My controllers all return a single ViewModel which specifies the content (see below) but how do I get it to also populate the sidebar?
public function detailsAction()
{
*some code to populate data*
$params = array('data' => $data);
$viewModel = new ViewModel($params);
$viewModel->setTemplate('school/school/details.phtml');
return $viewModel;
}
I've got a feeling I am doing something fundamentally wrong here.
In a controller you could use view models nesting and the layout plugin:
public function fooAction()
{
// Sidebar content
$content = array(
'name' => 'John'
'lastname' => 'Doe'
);
// Create a model for the sidebar
$sideBarModel = new Zend\View\Model\ViewModel($content);
// Set the sidebar template
$sideBarModel->setTemplate('my-module/my-controller/sidebar');
// layout plugin returns the layout model instance
// First parameter must be a model instance
// and the second is the variable name you want to capture the content
$this->layout()->addChild($sideBarModel, 'sidebar');
// ...
}
Now you just echo the variable in the layout script:
<?php
// 'sidebar' here is the same passed as the second parameter to addChild() method
echo $this->sidebar;
?>
You can include "sub templates" by using the partial view helper
<div id="main" class="span8 listings">
<?php echo $this->content; ?>
</div>
<div id="sidebar" class="span4">
<?php echo $this->partial('sidebar.phtml', array('params' => $this->params)); ?>
</div>
// Module.php add it is
use Zend\View\Model\ViewModel;
public function onBootstrap($e)
{
$app = $e->getParam('application');
$app->getEventManager()->attach('dispatch', array($this, 'setLayout'));
}
public function setLayout($e)
{
// IF only for this module
$matches = $e->getRouteMatch();
$controller = $matches->getParam('controller');
if (false === strpos($controller, __NAMESPACE__)) {
// not a controller from this module
return;
}
// END IF
// Set the layout template
$template = $e->getViewModel();
$footer = new ViewModel(array('article' => "Dranzers"));
$footer->setTemplate('album/album/footer');
$template->addChild($footer, 'sidebar');
}