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

7

我想在我的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');
}

我面临的问题是,JS文件没有被包含。这是否是包含JS文件的正确方式?

2个回答

13

JavaScript(以及图像、CSS、flash动画等)属于视图层,因此应该在那里进行配置。

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

<!-- 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>

你的视图脚本可以向辅助器添加资源,这些资源将在布局中被回显。由于布局使用了 prepend*() 方法,全局文件将首先显示,例如:

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

你好,你知道layout.pthml文件的默认位置在哪里吗?我在我的服务器上找不到它。 - Xitcod13
@Xitcod,Application\view\layout\layout.phtml - Dennis

1
在上面的解决方案中,“path/to/file.js”脚本将被包含在头部两次。在调用“prependFile”之前不需要使用“echo”。这种行为可能会导致重复的JavaScript控件。 headScript()->prependFile( $this->baseUrl('path/to/file.js')) // 这将输出整个prependFile队列


你是指我上面的回答吗?不确定你所说的被包含两次是什么意思。你的回答与我的相同。 - Phil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接