javascript 在 Zend 框架中包含 js 文件的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10100197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:42:38  来源:igfitidea点击:

the best way to include js file in zend framework

phpjavascriptzend-framework

提问by Rukmi Patel

I want to include external js file in my php script. I am following zend framework.Right now I am adding js file in controller's init function like this.

我想在我的 php 脚本中包含外部 js 文件。我正在关注 zend 框架。现在我正在像这样在控制器的 init 函数中添加 js 文件。

public function init() {
    $this->doUserAuthorisation();
    parent::init();
    $this->view->headScript()->appendFile($this->view->baseUrl().'/js/front_cal/jquery-1.3.2.min.js');  
    $this->view->headLink()->setStylesheet($this->view->baseUrl().'/styles/front_cal/calendar.css');
}

problem what i am facing is, js file doesnot include.Is this the right way to include js file?

我面临的问题是,js 文件不包含。这是包含 js 文件的正确方法吗?

回答by Phil

JavaScript (and images, CSS, flash movies, etc) belong to the view layer so configure them there.

JavaScript(和图像、CSS、Flash 电影等)属于视图层,所以在那里配置它们。

For globally included files, add them to your layout, eg

对于全局包含的文件,将它们添加到您的布局中,例如

<!-- layout.phtml -->
<head>
    <?php echo $this->headScript()->prependFile(
        $this->baseUrl('path/to/file.js')) ?>
    <?php echo $this->headLink()->prependStylesheet(
        $this->baseUrl('path/to/file.css')) ?>

<!-- snip -->

    <?php echo $this->inlineScript()->prependFile(
        'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js') ?>
</body>

Your view scripts can then add assets to the helpers which are echoed out in the layout. As the layout uses the prepend*()methods, the global files will be displayed first, eg

然后,您的视图脚本可以将资产添加到在布局中回显的助手。布局使用prepend*()方法时,会先显示全局文件,例如

<?php // views/scripts/index/index.phtml
$this->inlineScript()->appendFile($this->baseUrl('path/to/script.js'));

回答by Karol

In above solution the 'path/to/file.js' script will be included in the header twice. There is no need for echobefore calling prependFile. Such behaviour can lead to duplicating javascript controls.

在上面的解决方案中,'path/to/file.js' 脚本将被包含在标题中两次。echo调用之前不需要prependFile。这种行为会导致重复的 javascript 控件。

<!-- layout.phtml --> <head> <?php echo $this->headScript()->prependFile( $this->baseUrl('path/to/file.js')) // this will echo out the whole prependFile queue

<!-- layout.phtml --> <head> <?php echo $this->headScript()->prependFile( $this->baseUrl('path/to/file.js')) // this will echo out the whole prependFile queue