2013-12-13 30 views
0

我們正在使用Yii作爲我們的項目。我試圖在頭文件中有條件地註冊兩個JS腳本/資產:一個用於IE8,一個用於其他瀏覽器 - 使用條件註釋(例如<!--[if lte IE 8]>)。在Yii的控制器中顯示自定義HTML <head>

但是,我只熟悉Yii::app()->clientScript->registerScriptFileYii::app()->clientScript->registerScript,其中沒有一個公開了用條件註釋包圍已註冊腳本的方法。

我試圖直接做echo在控制器動作的開始:

echo '<!--[if lte IE 8]><script src="'.$assetsPath . '/charts/r2d3.js'.'" charset="utf-8"></script><![endif]-->'; 

然而,當我在看劇本時(之前甚至<html>)顯示在文檔的頂部源。如果可能,我想在<head>中顯示它。

回答

1

您可以使用下面的擴展

http://www.yiiframework.com/extension/ewebbrowser/

我將文件放入組件中。然後只是在代碼中做

$b = new EWebBrowser(); 
if($b->platform == "Internet Explorer" && $b->version == "8.0") {//you could explode version at the . I guess, however not sure if there is even a version 8.x or whatever 
    Yii::app()->clientScript->registerScriptFile("path/to/script"); 
} else { 
    Yii::app()->clientScript->registerScriptFile("path/to/otherscript"); 
} 

我用當前的IE,Firefox和Chrome瀏覽器測試過這個。我無法確保這可以與這些瀏覽器的其他版本一起使用。它兩歲了,但它似乎仍在工作。

1

你可以在頭下面設置此,

進入 - >則須─> layouts-> main.php

簡單的添加你需要經過不斷的內容,

<!DOCTYPE html> 
[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif] 
[if IE 7]><html class="no-js lt-ie9 lt-ie8"> <![endif] 
[if IE 8]><html class="no-js lt-ie9"> <![endif] 
[if gt IE 8]><html class="no-js"> <![endif] 
<head> 
    <meta charset="utf-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
</head> 

或者如果您需要檢查瀏覽器版本,在控制器中並追加腳本。這種方式也會起作用。

在控制器定義此,

public function beforeRender($view) { 
//condition to check the browser type and version 
if($browser = 'ie' && $version = '8') { 
    Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/script.js'); 
    return true; 
} 
} 

//還沒有測試的第二個選項。但應該工作。

您可以用以下任一檢查瀏覽器類型和版本,

<?php 
echo $_SERVER['HTTP_USER_AGENT']; 

$browser = get_browser(null, true); 
print_r($browser); 
?> 

檢查這個環節,http://php.net/manual/en/function.get-browser.php#101125

0

這不是最佳方法,但使用下面的代碼就可以實現你的目標:如果你想以上特定控制器條件語句,然後

在你的佈局/主。PHP

<?php if (Yii::app()->getController()->getId() == 'Your Controller Name'): ?> 
<!--[if lt IE 8]> 
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ie.css" media="screen, projection" /> 
<![endif]--> 
<?php endif; ?> 

如果你想上面的條件語句特別控制器行動,則:

在你的佈局/ main.php

<?php if (Yii::app()->getController()->getId() == 'Your Controller Name' && Yii::app()->getController()->getAction()->getId() == 'Your Action Name'): ?> 
<!--[if lt IE 8]> 
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ie.css" media="screen, projection" /> 
<![endif]--> 
<?php endif; ?>