4

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

Tom Martin
  • 441
  • 4
  • 5

2 Answers2

3

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.

aimfeld
  • 2,931
  • 7
  • 32
  • 43
1

Thank You Wunibald,

Your example worked perfectly, I have modified it below to be attached to an event so that it applies to every controller/module. To do this I have included it into the onBootstrap function in my Application module.

$events = StaticEventManager::getInstance();

    $events->attach('Zend\\Mvc\\Application', 'dispatch', function(\Zend\EventManager\Event $event)
    {
        $baseUrl = $event->getRouter()->getBaseUrl();
        $renderer = $event->getApplication()->getServiceManager()->get('Zend\View\Renderer\PhpRenderer');

        $action = $event->getRouteMatch()->getParam('action');
        $controller = $event->getRouteMatch()->getParam('controller');

        if (strlen($controller) > 0)
        {
            list($module, $_null, $controller) = explode('\\', $controller);

            $renderer->headScript()->appendFile($baseUrl . '/module/' . $module . '/view/' . strtolower($module) . '/' . strtolower($controller) . '/' . strtolower($action) . '.js');
            $renderer->headScript()->appendFile($baseUrl . '/module/' . $module . '/view/' . strtolower($module) . '/' . strtolower($module) . '.js');
        }
    });

Once again thank you for pointing me in the right direction.

Tom Martin
  • 441
  • 4
  • 5