Zend Framework 2 - 在布局中获取控制器和操作名称

i have tried to get controller name and action name in layout file. But could not. In ZF1, we have used Front Controller instance to get the controller and action name. I have surfed the websites a lot. But there is no solution. How can i get in ZF2?

Controllers and their view scripts are decoupled. In fact, there could be several controllers involved in a single request.

If you want the controller and action the request got dispatched to, you can inject them by hooking into the dispatch event and inject the controller and action name in the attached ViewModel.

One way of doing that is inside the Bootstrap Event which should be in the Module class.

public function onBootstrap(\Zend\EventManager\EventInterface $e)
{
    $app = $e->getApplication();
    $app->getEventManager()->attach(
        'dispatch',
        function($e) {
            $routeMatch = $e->getRouteMatch();
            $viewModel = $e->getViewModel();
            $viewModel->setVariable('controller', $routeMatch->getParam('controller'));
            $viewModel->setVariable('action', $routeMatch->getParam('action'));
        },
        -100
    );

I got the above answer to work but I had to use the sharedManager to pass on the view to the controller

    $app = $e->getApplication();
    $app->getEventManager()->getSharedManager()->attach(
        __NAMESPACE__,
        'dispatch',
        function($e) {
            $routeMatch = $e->getRouteMatch();
            $viewModel = $e->getViewModel();
            $viewModel->setVariable('controller', $routeMatch->getParam('controller'));
            $viewModel->setVariable('action', $routeMatch->getParam('action'));
            $controller = $e->getTarget();
            $controller->view = $viewModel;
        },
        100
    );

If I wanted to use the above answer as is I had to do

    $this->getEvent('dispatch')->getViewModel()

in the controller