Search code examples
zend-framework2viewrendering

How to get the current view being rendered inside ZF2


Is there a way to get the current view being rendered inside zend framework 2?

I believe this should be possible with the event system but I can't seem to make it work.

The reason I want to get this information is so I can automatically include a .js file with the same name, this would save me time having to specify this rule each time i'm inside a action.

Many thanks, Tom


Solution

  • I'm not quite sure what you mean by rendering the current view inside ZF2, but here's how you can add a js file named after the action automatically. Just put this in your controller:

    public function onDispatch(MvcEvent $mvcEvent)
    {
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\PhpRenderer');
        $actionName = $mvcEvent->getRouteMatch()->getParam('action');
        $jsFile = $actionName . '.js';
        $baseUrl = $mvcEvent->getRouter()->getBaseUrl();
        $renderer->headScript()->appendFile($baseUrl . '/js/' . $jsFile);
    
        return parent::onDispatch($mvcEvent);
    }
    

    You may need to adjust the code for your js file location and name of course. The onDispatch method is called automatically before the action.