I had similar instances on where I had to do this on my application.
To add a Javascript depending on what Controller is loaded, you do this:
<?php class ReportController extends Zend_Controller_Action { public function init() { $this->view->headScript()->appendFile('path/to/the/javascript/file'); } /* rest of the code here */ } |
I think this also works with CSS, and others.
UPDATE:
This really does work Pretty cool Now we do not have to put all those if-conditions in the layout.
For headScript, headMeta and headLink to work, you must echo headScript(), headMeta() and headStyle() respectively in the layout head tag.
<?php // application/layouts/scripts/layout.phtml echo $this->doctype() ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <?php echo $this->headMeta() ?> <?php echo $this->headScript() ?> <?php echo $this->headStyle() ?> </head> <body> |
Aha very useful, I wasn’t aware of this method, thanks for sharing! -Jason
hi jason, I’m glad you found it useful
very useful tips..I don’t know about this. Zend make it easier to add javascript for each controller. Thanks
that’s what i was looking for
Thanks for the info.
But what if there are some default libs to include on the layout and then from the controller add custom ones on. The problem I have is it puts the lib in the controller first before the lib in the layout.
i.e.
// layout.php
$this->headScript()->appendFile(‘/js/jquery.js’, ‘text/javascript’)
// controller
$this->view->headScript()->appendFile(‘/js/jquery2.js’, ‘text/javascript’)
But I need jquery2.js to come after jquery1.js
Hey, sorry to bring up an old post.
I was doing things this way, but one bad think it trying to hunt down where js/css files where included from (from experience).
I started adding it to an ini file (separated by module name) and adding them from the bootstrap.
Now I have one location that contains all my js/css filenames.
Hi Jeremy,
Thanks for the tip! Do you have a sample code? It would be great if we can share and post it here.
Thanks,
Wenbert
Hi
@Eddie Jaoude:
you must put the libraries essential to your template in the layout. With the method ‘prependFile’, jquery.js will be the first. For example you write this line in your layout.phtml:
$this->headScript()->prependFile(‘/js/jquery.js’, ‘text/javascript’)
and for the other library essential just for the view script, i think it’s better in the view script than in the controller (because javascript is part of the view). And of course with the method ‘appendFile’. So in your view script for the action, write this line:
$this->headScript()->appendFile(‘/js/jquery2.js’, ‘text/javascript’)
So your jquery.js will be loading before jquery2.js