Zend Framework: Adding Javascript files depending on Controller

Posted on: May 15, 2009 by wenbert

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 :D Pretty cool :D 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>

Subscribe to comments Comment | Trackback |
Post Tags: , , , ,

Browse Timeline


Comments ( 7 )

Aha very useful, I wasn’t aware of this method, thanks for sharing! -Jason

Jason added these pithy words on May 18 09 at 11:37 PM

hi jason, I’m glad you found it useful ;-)

Wenbert added these pithy words on May 20 09 at 8:07 AM

very useful tips..I don’t know about this. Zend make it easier to add javascript for each controller. Thanks

deerawan added these pithy words on Sep 04 09 at 5:19 PM

that’s what i was looking for

marcin added these pithy words on Dec 18 09 at 1:40 AM

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

Eddie Jaoude added these pithy words on Jan 13 10 at 11:21 PM

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.

Jeremy added these pithy words on Jan 18 10 at 12:33 PM

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

Wenbert added these pithy words on Jan 18 10 at 4:05 PM

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!