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 文件的正确方法吗?

4

2 回答 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'));
于 2012-04-11T05:31:16.027 回答
1

在上述解决方案中,'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

于 2014-05-20T12:33:39.507 回答