php - Zend Framework 2: Composing web page of several parts

862

I need to compose a web page of several view templates (the view template rendering page content and a view template rendering sidebar). In my layout.phtml, I have two variable placeholders: $content and $sidebar:

......
<?php echo $this->sidebar; ?>
......
<?php echo $this->content; ?>
......

In my controller's action, I pass the data to these view templates through the ViewModels chained in a tree:

public function indexAction() {

 // Preparing my data
 // $form = ...
 // $menuItems = 
 // $activeItem =       

 // Create sidebar view model
 $sidebarViewModel = new ViewModel(array('menuItems'=>$menuItems, 'activeItem'=>$activeItem));
 // Add it as a child to layout view model
 $this->layout()->addChild($sidebarViewModel, 'sidebar');

 // Page content view model
 $viewModel = new ViewModel(array('form'=>$form));
 return $viewModel;     
}

But, because I have the sidebar on every page, I will have to copy and paste this code for every action of every controller. Is there any recommended way of reusing the code that populates the ViewModel for sidebar?

760

Answer

Solution:

One approach would be to achieve this with a controller plugin.

Assuming you have wired it up with appropriate config, and you're in the Application module.

Inmodule/Application/src/Application/Controller/Plugin/AddSidebar.php:

namespace Application\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class addSidebar extends AbstractPlugin {

    public function __invoke($menu, $active) {

        // create new view model
        $sidebarVM = new ViewModel(array(
            'menuItems'  => $menu,
            'activeItem' => $active
        ));

        // add it to the layout
        $this->getController()->layout()->addChild($sidebarVM, 'sidebar');

    }

}

Then in each of your controllers:

$this->addSidebar($menuItems, $activeItem);

Another (probably better) option would be to hook into the renderMvcEvent and add the sidebar there. You'd have to work out how to generate$menuItems and$activeItem in that context however.

People are also looking for solutions to the problem: php - Why does cannot modify header information etc cite the middle of an html block?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.