Reputation: 1050
It seems I remember that in Zend Framework, we could add styles/scripts via headScript in the action of a page. In Zend2, this doesn't seem to be an option.
I don't see much in the documentation about handling this. Basically my question is; is it proper to add these styles/scripts in the view? Or is there there a new way to add them in the controller action?
Thanks
Upvotes: 1
Views: 4689
Reputation: 3534
In your controller action:
$this
->getServiceLocator()
->get('viewhelpermanager')
->get('HeadScript')
->appendFile('/js/custom.js')
;
You could make this easier by creating an "invokable" "service locator aware" controller plugin.
You can do that in your modules config file:
...
'controller_plugins' => array(
'invokables' => array(
'Head' => 'Application\Controller\Plugin\Head',
)
),
...
Creating the "Head" class in module/Application/src/Application/Controller/Plugin/Head.php
that implements ServiceLocatorAwareInterface
and build some methods like javaScript()
or styleSheet
for example that simply grab the view helper and return it:
return $this
->getServiceLocator()
->getServiceLocator() // Main service Locator
->get('viewhelpermanager')
->get('HeadScript')
;
Then in your controller it's more like:
$this->Head()->javaScript()->appendFile('/js/custom.js');
You could get as fancy as you wanted about it though. Maybe even Magento style with the XML governing the layout per action.
UPDATE
Output is buffered if you're using the ZF2 MVC. So i've found that adding scripts and stylesheets to a page is best done from the template file attached to your view model:
$this->headScript()->appendFile('/js/custom.js', 'text/javascript');
$this->headLink()->appendStylesheet('/css/custom.css');
Keep it out of the controller since it is view related.
Upvotes: 9
Reputation: 2839
I'm don't understand what about Marshall House talk.
Plugin need implements PluginInterface. Why implements ServiceLocatorAwareInterface ?
Where paste this code?
return $this
->getServiceLocator()
->getServiceLocator() // Main service Locator
->get('viewhelpermanager')
->get('HeadScript');
Also AbstractPlugin (if extend from it) doesn't have getServiceLocator() methos. What it mean? Main service Locator? Please write some example.
Upvotes: 0