2012-04-11 67 views
6

我想在我的php腳本中包含外部js文件。我正在遵循zend framework.Right現在我正在像這樣在控制器的init函數中添加js文件。在zend框架中包含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文件doesnot include.Is這是正確的方式來包含js文件?

回答

12

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')); 
+0

嘿,你知道layout.pthml的默認位置?我無法在我的服務器上找到它。 – Xitcod13 2015-01-24 01:43:11

+0

@Xitcod,'Application \ view \ layout \ layout.phtml' – Dennis 2017-08-04 20:56:23

2

在上述溶液中的「路徑/到/ file.js」腳本將被包括在報頭的兩倍。在致電prependFile之前,不需要echo。這種行爲會導致重複的javascript控制。

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

+0

你的意思是我上面的答案嗎?不知道你的意思是包括兩次。你的答案與我的相同部分完全相同 – Phil 2014-10-23 22:24:53

相關問題