You can use a view helper to load javascript and css files on a per controller/view basis. This is something I have experimented with and I find it quite helpful, although I haven't taken the step of putting it into a live project yet, I'm still assessing it.
Here is the devzone article I got the idea from. All credit to Andy Baird for posting the technique.
Basically you setup two view helpers, one for javascript:-
class Zend_View_Helper_JavascriptHelper extends Zend_View_Helper_Abstract
{
function javascriptHelper() {
$request = Zend_Controller_Front::getInstance()->getRequest();
$file_uri = 'media/js/' . $request->getControllerName() . '/' . $request->getActionName() . '.js';
if (file_exists($file_uri)) {
$this->view->headScript()->appendFile('/' . $file_uri);
}
}
}
and one for css:-
class Zend_View_Helper_CssHelper extends Zend_View_Helper_Abstract
{
function cssHelper() {
$request = Zend_Controller_Front::getInstance()->getRequest();
$file_uri = 'media/css/' . $request->getControllerName() . '/' . $request->getActionName() . '.css';
if (file_exists($file_uri)) {
$this->view->headLink()->appendStylesheet('/' . $file_uri);
}
return $this->view->headLink();
}
}
Then you call them from your layout script:-
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My app title</title>
<? $this->headLink()->appendStylesheet('/media/css/global.css') ?>
<? $this->headLink()->appendStylesheet('/media/css/iefix.css','screen','lt IE 7') ?>
<?= $this->cssHelper() ?>
<? $this->headScript()->appendFile('/media/js/jquery-1.3.2.min.js') ?>
<? $this->headScript()->appendFile('/media/js/global.js') ?>
<? $this->javascriptHelper() ?>
<?= $this->headScript() ?>
</head>
You then store your javascript and css files in folders that reflect the name of the action they are used with, for example:-
media/js/index/index.js
media/css/index/index.css
to load css and javascript for you index action.
In practice I have found it preferable to put javascript and css in the same folder, so I miss out the js
& css
parts of the paths above and adjust the $file_url
variable in both helpers accordingly.