zend framework 3 append script from controller

964 views Asked by At

Is it still possible to dynamically append script/files depending on the context?

I saw here it was possible in ZF1 but that doesn't work in ZF3.

Any Ideas?

1

There are 1 answers

1
avy On BEST ANSWER

You can do this but you need to inject the 'Head Script' view helper into the controller:

// controller factory
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
    // get service manager
    $serviceLocator = $container->getServiceLocator();

    // get view helper manager
    $viewHelperManager = $sm->get('ViewHelperManager');

    // get 'head script' plugin
    $headScript = $viewHelperManager->get('headScript');

    return new SomeController($headScript);
}

Then in the controller:

public function __construct($headScript)
{
    $this->headScript = $headScript;
}

public function someAction()
{
    // append file, etc.
    $this->headScript->appendFile('some-js');
    //...
}

But the fact that this plugin is provided as a view helper suggests that they were expecting you to do this in the view, not in the controller. In that case it's much simpler:

// in views/some/view.phtml
// no injection needed
$this->headScript()->appendFile('some-js');

If possible it would be cleaner to refactor your code so that you are injecting any variables you need to test as conditions for adding the js into the view model.