简体   繁体   English

如何从Controller(Zend Framework)控制布局中加载的js文件

[英]How to control the js files that are load in layout, from the Controller (Zend Framework)

First of all, I'm a beginner in Zend Framework and maybe there is a simple way of doing this but i don't know it. 首先,我是Zend Framework的初学者,也许有一个简单的方法可以做到这一点,但我不知道。

What I am trying to achieve is to load different js files (in layout head) depending on what Controller is used. 我要实现的目标是根据所使用的Controller加载不同的js文件(在布局头中)。 I can't add the js files as variables to the Layout object because the layout is disabled in those Controllers. 我无法将js文件作为变量添加到Layout对象,因为在那些Controller中禁用了布局。

What's the proper way to do it? 正确的做法是什么? Thank you. 谢谢。

Edit (the code) 编辑(代码)

In the CalendarController (using Subdigger's method): 在CalendarController中(使用Subdigger的方法):

    public function init()
    {
      $this->_helper->layout->disableLayout();

      $js = new Application_View_Helper_Javascript();
      //get an array with the basename of the js files          
      $jsFiles = $js->addFiles('calendar');

      foreach ($jsFiles as $k=>$file){
           $this->view->headScript()->appendFile('/js/' . $file.'.js');
      }


    }

And in the layout.phtml: 并在layout.phtml中:

<?php
 echo $this->doctype()."\n";
 ?>
 <html>
    <head>
       <?php
         echo $this->headMeta()."\n";
         echo $this->headLink()."\n";
         echo $this->headTitle()."\n";
         echo $this->headScript()."\n";

you can go by this way: in controller 你可以这样:在控制器中

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        $this->view->headScript()->appendFile(
          '/js/prototype.js',
          'text/javascript',
          array('conditional' => 'lt IE 7')
        );
    }
......
}

then in view: 然后来看:

.....
  <head>
    <?php echo $this->headScript() ?>
  </head>
.....

read this 这个

I understand your problem but not your intentions correctly. 我了解您的问题,但未正确理解您的意图。 You say in a comment that the layout is enabled in the indexController but the others have the layout disabled. 您在注释中说,已在indexController中启用了布局,但其他人禁用了布局。 If you dispatch to another controller and disable the layout the layout.phtml should not be used. 如果您调度到另一个控制器并禁用布局,则不应使用layout.phtml。 So, how do you use it? 那么,您如何使用它呢? Do you have an include somewhere? 您是否在某个地方包含了?

I think the solution here is not to disable the layout but to load a different layout in those "other" controllers. 我认为这里的解决方案不是禁用布局,而是在那些“其他”控制器中加载其他布局。

$this->_helper->layout->setLayout('foobaz');

You can load a different layout for each controller or even action in a controller. 您可以为每个控制器甚至是控制器中的动作加载不同的布局。 Another thing I noticed is that you load it in the init() method. 我注意到的另一件事是,您将其加载到init()方法中。 I do all this logic in the actions or pre/postDispatch methods. 我在动作或pre / postDispatch方法中执行所有这些逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM