我试图将多个js文件添加到布局中。我想在帮手里做这件事 这是我帮手的代码:
// class Zend_View_Helper_LoadJs extends Zend_View_Helper_Abstract
public function loadJs()
{
$dir = '../public/js';
$dir = scandir($dir);
$jsFiles = array();
foreach($dir as $key => $value)
{
if($value != '.' && $value != '..')
$jsFiles[] = $value;
}
if(is_array($jsFiles)){
foreach($jsFiles as $key => $val)
{
$this->view->headScript()->appendFile($this->view->baseUrl('js/'.$val));
}
}
}
在我的布局中,我有:
<?php $this->loadJs(); ?>
问题是它没有添加任何js文件 如果我之前把回音:
echo $this->view->headScript()->appendFile($this->view->baseUrl('js/'.$val));
或
<?php echo $this->loadJs(); ?>
然后脚本会添加相同文件的几次 有人可以告诉我,我做错了什么?
答案 0 :(得分:0)
试试这个(评论显示变化):
的 [编辑] 强>
好吧,我想我明白了。为了使用这个帮助器填充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 -->
我希望它也适合你。