试试这个(评论显示更改):
[编辑]
好的,我想我明白了。为了使用这个助手来填充headscript()
堆栈,我们必须将结果注册到视图渲染器。
public function loadJs() {
$dir = '../public/js';
$dir = scandir($dir);
//get bootstrap
$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
//get current view renderer
$view = $bootstrap->getResource('view');
$jsFiles = array();
foreach ($dir as $key => $value) {
if (!is_dir($value))
$jsFiles[] = $value;
}
if (is_array($jsFiles)) {
foreach ($jsFiles as $key => $val) {
if (strpos($val, '.js') != FALSE) {
//assign file to headscript stack in the cuurent view renderer
$view->headScript()->appendFile($this->view->baseUrl('js/' . $val)). "\n";
}
}
}
}
现在,当我们headscript()
在布局中回显时,这些文件将被渲染一次。
仅供参考,init()
我在引导程序中执行我的视图:
//truncated because it's too long...
protected function _initView()
{
//Initialize view
$view = new Zend_View();
//set doctype for default layout
$view->doctype(Zend_Registry::get('config')->resources->view->doctype);
//set css includes
$view->headLink()->setStylesheet('/css/normalize.css');
//add javascript files
$view->headScript()->setFile('/javascript/modernizr.js');
//add it to the view renderer
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
'ViewRenderer');
$viewRenderer->setView($view);
//Return it, so that it can be stored by the bootstrap
return $view;
}
然后我在布局中使用了助手,如:
<?php echo $this->doctype() . "\n" ?>
<?php $this->LoadJs() ?>
<html>
<head>
<?php echo $this->headTitle() . "\n"; ?>
<?php echo $this->headMeta() . "\n"; ?>
<?php echo $this->headLink() . "\n" ?>
<?php echo $this->headscript() . "\n" ?>
<!--[if IE]><script type="text/javascript" src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
</head>
这样做,LoadJs()
不会直接渲染任何东西,而是该方法只是将文件转储到headscript()
占位符上。
我的结果:
<script type="text/javascript" src="/javascript/modernizr.js"></script> <!--added by bootstrap -->
<script type="text/javascript" src="/javascript/mediaelement/build/jquery.js"></script> <!-- added by bootstrap -->
<script type="text/javascript" src="http://schoenwolf.local/javascript/modernizr.js"> </script><!-- added by LoadJs -->
我希望它也适用于你。