如何将变量发送到ZF3中的错误布局?

时间:2019-04-19 14:44:23

标签: zend-framework zend-framework2 zend-framework3 zend-view

将变量发送到布局模板的正确方法是什么,因为它可以在错误页面中找到?

我在所有前端控制器上方都有AppFrontController。在onDispatch()方法中有代码(代码在附近):

 $assocArrayOfVars = $this->MyPlugin()->getDbVariablesArray();
  foreach($assocArrayOfVars as $name => $value){
     $this->layout()->$name = $value;
  }

  list($catalog, $count_goods) = $this->MyPlugin()->getStandardCatalogDataForLayout();
  $this->layout()->catalog = $catalog;
  $this->layout()->count_goods = $count_goods;

结果,我在每个前端页面中都有我的局部变量。但是我没有在错误页面中看到它。我该如何解决这个问题?我非常需要您的建议!谢谢!

1 个答案:

答案 0 :(得分:0)

谢谢您的建议!问题解决了。最终版本Module.php文件的代码如下。根据froschdesign的建议,我使用侦听器而不是“父控制器”。

 public function onBootstrap(MvcEvent $event)
   {
      $application = $event->getApplication();
      $eventManager = $application->getEventManager();
      $eventManager->attach('dispatch', array($this, 'loadConfiguration'), 2);
      $eventManager->attach('dispatch.error', array($this, 'loadConfiguration'), 2);
}


 public function loadConfiguration(MvcEvent $e)
   {
      $application = $e->getApplication();
      $sm = $application->getServiceManager();
      $sharedManager = $application->getEventManager()->getSharedManager();

      $router = $sm->get('router');
      $request = $sm->get('request');

      $zendCart = $sm->get('ControllerPluginManager')->get('ZendCart');
      $myPlugin = $sm->get('ControllerPluginManager')->get('MyPlugin');
      $viewModel = $e->getViewModel();

      $viewModel->setVariable('total', $zendCart->total());
      $viewModel->setVariable('total_items', $zendCart->total_items());

      $viewModel->setVariable('rusmonth', $rusmonth);

      /* Layout variables */
      $assocArrayOfVars = $myPlugin->getDbVariablesArray();
      foreach ($assocArrayOfVars as $name => $value) {
         $viewModel->setVariable($name, $value);
      }

      list($catalog, $count_goods) = $myPlugin->getStandardCatalogDataForLayout();
      $viewModel->setVariable('catalog', $catalog);
      $viewModel->setVariable('count_goods', $count_goods);

   }

更多监听器示例here