在<;头部>;来自Yii的控制器


Display Custom HTML in <head> From Controller in Yii

我们的项目使用Yii。我试图在头中有条件地注册两个JS脚本/资产:一个用于IE8,另一个用于其他浏览器——使用条件注释(例如<!--[if lte IE 8]>)。

然而,我只熟悉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>中。

您可以使用以下扩展

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浏览器进行了测试。我不能确保这将与这些浏览器的其他版本一起工作。它已经两年了,但似乎仍然有效。

您可以在head中设置如下,

转到->views->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

这不是最佳方法,但您可以使用以下代码实现目标:

如果您想要特定控制器的上述条件语句,则:

下方布局/main.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; ?>