javascriptphpyiiclientscript

Display Custom HTML in <head> From Controller in Yii


We are using Yii for our project. I am trying to conditionally register two JS scripts/assets in the header: one for IE8 and one for other browsers - using conditional comments (e.g. <!--[if lte IE 8]>).

However, I am only familiar with Yii::app()->clientScript->registerScriptFile and Yii::app()->clientScript->registerScript, none of which exposes a way to surround the registered script with a conditional comment.

I tried directly doing echo at the start of the controller action:

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

However, when I look in the source the script is displayed at the top of the document (before even <html>). If possible, I'd like to display it in <head>.


Solution

  • You could use the following extension

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

    I put the file in component. Then just do in the code

    $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");
    }
    

    I did test this with the current IE, Firefox and Chrome browser. I can not ensure this would work with other version of these browser. It two years old, but it still seems to be working.