Include CSS,javascript file in Yii Framework

JavascriptPhpCssYii

Javascript Problem Overview


How to include a Javascript or CSS file in Yii Framework?

I want to create a page on my site that has a little Javascript application running, so I want to include .js and .css files in a specific view.

Javascript Solutions


Solution 1 - Javascript

Something like this:

<?php  
  $baseUrl = Yii::app()->baseUrl; 
  $cs = Yii::app()->getClientScript();
  $cs->registerScriptFile($baseUrl.'/js/yourscript.js');
  $cs->registerCssFile($baseUrl.'/css/yourcss.css');
?>

Solution 2 - Javascript

You can do so by adding

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/script');

Solution 3 - Javascript

I liked to answer this question.

Their are many places where we have css & javascript files, like in css folder which is outside the protected folder, css & js files of extension & widgets which we need to include externally sometime when use ajax a lot, js & css files of core framework which also we need to include externally sometime. So their are some ways to do this.

Include core js files of framework like jquery.js, jquery.ui.js

<?php 
Yii::app()->clientScript->registerCoreScript('jquery'); 	
Yii::app()->clientScript->registerCoreScript('jquery.ui'); 
?>

Include files from css folder outside of protected folder.

<?php 
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/example.css');
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/css/example.js');
?>

		

Include css & js files from extension or widgets.

Here fancybox is an extension which is placed under protected folder. Files we including has path : /protected/extensions/fancybox/assets/

<?php
// Fancybox stuff.
$assetUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.fancybox.assets'));
Yii::app()->clientScript->registerScriptFile($assetUrl.'/jquery.fancybox-1.3.4.pack.js'); 
Yii::app()->clientScript->registerScriptFile($assetUrl.'/jquery.mousewheel-3.0.4.pack.js'); 
?>	

Also we can include core framework files: Example : I am including CListView js file.

<?php
$baseScriptUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets'));
Yii::app()->clientScript->registerScriptFile($baseScriptUrl.'/listview/jquery.yiilistview.js',CClientScript::POS_END);	
?>
  • We need to include js files of zii widgets or extension externally sometimes when we use them in rendered view which are received from ajax call, because loading each time new ajax file create conflict in calling js functions.

For more detail Look at my blog article

Solution 4 - Javascript

Easy in your conf/main.php. This is my example with bootstrap. You can see that here

'components'=>array(
    'clientScript' => array(
        'scriptMap' => array(
            'jquery.js'=>false,  //disable default implementation of jquery
            'jquery.min.js'=>false,  //desable any others default implementation
            'core.css'=>false, //disable
            'styles.css'=>false,  //disable
            'pager.css'=>false,   //disable
            'default.css'=>false,  //disable
        ),
        'packages'=>array(
            'jquery'=>array(                             // set the new jquery
                'baseUrl'=>'bootstrap/',
                'js'=>array('js/jquery-1.7.2.min.js'),
            ),
            'bootstrap'=>array(                       //set others js libraries
                'baseUrl'=>'bootstrap/',
                'js'=>array('js/bootstrap.min.js'),
                'css'=>array(                        // and css
                    'css/bootstrap.min.css',
                    'css/custom.css',
                    'css/bootstrap-responsive.min.css',
                ),
                'depends'=>array('jquery'),         // cause load jquery before load this.
            ),
        ),
    ),
),

Solution 5 - Javascript

In the view, add the following:

<?php  
  $cs = Yii::app()->getClientScript();
  $cs->registerScriptFile('/js/yourscript.js', CClientScript::POS_END);
  $cs->registerCssFile('/css/yourcss.css');
?>

Please notice the second parameter when you register the js file, it's the position of your script, when you set it CClientScript::POS_END, you let the HTML renders before the javascript is loaded.

Solution 6 - Javascript

Do somthing like this by adding these line to your view files;

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/javascript/file');
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/path/to/css/file');

Solution 7 - Javascript

To include JS and CSS files in a specific view you can do it via controller by passing the parameters false, true, which will include the CSS and JS for, e.g.:

$this->renderPartial(
    'yourviewname',
    array(
        'model' => $model,
        false,
        true
    )
);

Solution 8 - Javascript

There are many methods that we can include javascript, css into your Yii App. Today I will demonstrate three simple and helpul methods.

A simple way to add js, css by editing config/main.php

// application components
  'components'=>array(
         // ...
        'clientScript'=>array(
            'packages'=>array(
                'jquery'=>array(
                    'baseUrl'=>'//ajax.googleapis.com/ajax/libs/jquery/1/',
                    'js'=>array('jquery.min.js'),
                )
            ),
        ),
        // ...
  ),

Using getClientScript

Usually, We add in block of code into Controller or layout of your theme

$baseUrl = Yii::app()->baseUrl; 
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl.'/js/yourscript.js');
$cs->registerCssFile($baseUrl.'/css/yourcss.css');

Or shorter:

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/javascript/file',CClientScript::POS_END);
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/path/to/css/file');

Include core js files

Yii::app()->clientScript->registerCoreScript('jquery');     
Yii::app()->clientScript->registerCoreScript('jquery.ui');

Faster Yii API Document: http://yii.codexamples.com/

Solution 9 - Javascript

here is a good solution to use CDN and offline scripts

I use this code in every application I build, so you can use this in any app.

Included Scripts:

  • main.css
  • main.js
  • jQuery
  • jQuery / CD
  • Bootstrap 3.1
  • Bootstrap 3.1 / CDN
  • Fancybox 2
  • Fancybox 2 / CDN
  • FontAwesome 4
  • FontAwesome 4 / CDN
  • Google Analytics Script

STEP1:

put this code in config/main.php

		'params'=>array(
			'cdn'=>true, // or false
...

STEP2:

create resoreses folder in root app folder and put your script there

res/
--js
--css
--img
--lib
--style
..

STEP3:

put this code in components/controller.php

public function registerDefaults() 
{
    $cs = Yii::app()->clientScript;

    if (Yii::app()->params['cdn']){
        $cs->scriptMap = array(
            'jquery.js' => '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js',
            'jquery.min.js' => '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js',
        );
        $cs->packages = array(
            'bootstrap' => array(
                'basePath' => 'application.res',
                'baseUrl' => '//netdna.bootstrapcdn.com/bootstrap/3.1.1/',
                'js' => array('js/bootstrap.min.js'),
                'css' => array('css/bootstrap.min.css'),
                'depends' => array('jquery')
            ),
        );
    } else {
        $cs->packages = array(
            'bootstrap' => array(
                'basePath' => 'application.res',
                'baseUrl' => Yii::app()->baseUrl . '/res/lib/bootstrap/',
                'js' => array('js/bootstrap.js'),
                'css' => array('css/bootstrap.css'),
                'depends' => array('jquery')
            ),
        );
    }

	$cs->registerPackage('bootstrap');
		
	$cs->registerCSSFile(Yii::app()->baseUrl . '/res/style/main.css');
    $cs->registerScriptFile(Yii::app()->baseUrl . '/res/js/main.js');
}

public function registerFancybox($buttons = false, $thumbs = false) 
{
    $cs = Yii::app()->clientScript;

    $cs->packages = array(
        'fancybox' => array(
            'basePath' => 'application.res',
            'baseUrl' => Yii::app()->baseUrl . '/res/lib/fancybox/',
            'js' => array('lib/jquery.mousewheel-3.0.6.pack.js', 'source/jquery.fancybox.pack.js'),
            'css' => array('source/jquery.fancybox.css'),
            'depends' => array('jquery')
        ),
        'fancybox-buttons' => array(
            'basePath' => 'application.res',
            'baseUrl' => Yii::app()->baseUrl . '/res/lib/fancybox/source/helpers/',
            'js' => array('jquery.fancybox-buttons.js'),
            'css' => array('jquery.fancybox-buttons.css'),
        ),
        'fancybox-thumbs' => array(
            'basePath' => 'application.res',
            'baseUrl' => Yii::app()->baseUrl . '/res/lib/fancybox/source/helpers/',
            'js' => array('jquery.fancybox-thumbs.js'),
            'css' => array('jquery.fancybox-thumbs.css'),
        )
    );

    $cs->registerPackage('fancybox');
    if ($buttons)
        $cs->registerPackage('fancybox-buttons');
    if ($thumbs)
        $cs->registerPackage('fancybox-thumbs');
}

public function registerFontAwesome(){

    $cs = Yii::app()->clientScript;

    if (Yii::app()->params['cdn']):
        $cs->packages = array(
            'fontAwesome' => array(
                'basePath' => 'application.res',
                'baseUrl' => '//netdna.bootstrapcdn.com/font-awesome/4.0.0/',
                'css' => array('css/font-awesome.min.css'),
            )
        );
    else:
        $cs->packages = array(
            'fontAwesome' => array(
                'basePath' => 'application.res',
                'baseUrl' => Yii::app()->baseUrl . '/res/lib/font-awesome/',
                'css' => array('/css/font-awesome.min.css'),
            )
        );
    endif;

    $cs->registerPackage('fontAwesome');
}

public function registerGoogleAnalytics()
{
	if($this->config('settings_google_analytics_id')){
		Yii::app()->clientScript->registerScript('GA',"
			(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
			(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
			m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
			})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

			ga('create', '".Yii::app()->params['cdn']."', '{$_SERVER['SERVER_NAME']}');
			ga('send', 'pageview');
		");
	}
}

STEP4:

call the functions like this in //layouts/main.php

Yii::app()->getController()->registerDefaults();
Yii::app()->getController()->registerFontAwesome();
Yii::app()->getController()->registerGoogleAnalytics();

Solution 10 - Javascript

Also, if you want to add module assets both CSS and JS, you can use the following logic. See how you need to indicate the correct path to getPathOfAlias:

public static function register($file)
{
    $url = Yii::app()->getAssetManager()->publish(
    Yii::getPathOfAlias('application.modules.shop.assets.css'));

    $path = $url . '/' . $file;
    if(strpos($file, 'js') !== false)
        return Yii::app()->clientScript->registerScriptFile($path);
    else if(strpos($file, 'css') !== false)
        return Yii::app()->clientScript->registerCssFile($path);

    return $path;
}

The above code has been taken from GPLed Yii based Webshop app.

Solution 11 - Javascript

You can also add scripts from controller action. Just add this line in an action method then that script will apear only in that view:

Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl . '/js/custom.js', CClientScript::POS_HEAD);

where POS_HEAD tell framework to put script in head section

Solution 12 - Javascript

In Yii framework, You can include js and css using below method.

Including CSS:

{Yii::app()->request->baseUrl}/css/styles.css

Including JS:

{Yii::app()->request->baseUrl}/js/script.js

Including Image:

{Yii::app()->request->baseUrl}/images/logo.jpg

Note: By using layout concept in yii, You can add css and js instead of specifying in view template.

Solution 13 - Javascript

> Add the CSS and JS in The Layout Folder.Access anywhere in the project

  <!--// Stylesheets //-->
    <?php
        $themepath=Yii::app()->theme->baseUrl;
        Yii::app()->clientScript->registerCoreScript("jquery");
    ?>
    	
        <link href="<?php echo $themepath."/css/custom.css"; ?>" rel="stylesheet" media="all" />


<!--// Javascript //-->
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
</script> -->
<script type="text/javascript" src="<?php echo $themepath; ?>/js/video.min.js"></script>

Solution 14 - Javascript

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="/news/js/popup.js"></script>

link must input over the first php tag in the view pag

Solution 15 - Javascript

Using bootstrap extension

my css file: themes/bootstrap/css/style.css

my js file: root/js/script.js

at theme/bootstrap/views/layouts/main.php

<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/styles.css" />

<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/script.js"></script>

Solution 16 - Javascript

This was also an easy way to add script and css in main.php

<script src="<?=Yii::app()->theme->baseUrl; ?>/js/bootstrap.min.js"></script>
<link href="<?=Yii::app()->theme->baseUrl; ?>/css/bootstrap.css" rel="stylesheet" type="text/css">

Solution 17 - Javascript

If you are using Theme then you can the below Syntax

Yii::app()->theme->baseUrl

include CSS File :

<link href="<?php echo Yii::app()->theme->baseUrl;?>/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">

Include JS File

<script src="<?php echo Yii::app()->theme->baseUrl;?>/js/jquery-2.2.3.min.js"></script>

If you are not using theme

Yii::app()->request->baseUrl

Use Like this

<link href="<?php echo Yii::app()->request->baseUrl; ?>/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">
<script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery-2.2.3.min.js"></script>

Solution 18 - Javascript

  • In Yii Assets are declared in engine/assets/Appassets.php This make more easier to manage all your css and js files enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvijiView Question on Stackoverflow
Solution 1 - JavascriptAlexander HramovView Answer on Stackoverflow
Solution 2 - JavascriptysingView Answer on Stackoverflow
Solution 3 - JavascriptOnkar JanwaView Answer on Stackoverflow
Solution 4 - JavascriptKnito AuronView Answer on Stackoverflow
Solution 5 - JavascriptMohammad AniniView Answer on Stackoverflow
Solution 6 - JavascriptChaulagaiView Answer on Stackoverflow
Solution 7 - JavascriptWasim PathanView Answer on Stackoverflow
Solution 8 - JavascriptTruongnqView Answer on Stackoverflow
Solution 9 - JavascriptAbudayahView Answer on Stackoverflow
Solution 10 - JavascriptEyeView Answer on Stackoverflow
Solution 11 - JavascriptgSorryView Answer on Stackoverflow
Solution 12 - JavascriptBeginnerView Answer on Stackoverflow
Solution 13 - JavascriptElango ManiView Answer on Stackoverflow
Solution 14 - Javascripttrai buiView Answer on Stackoverflow
Solution 15 - JavascriptVictor AzevedoView Answer on Stackoverflow
Solution 16 - JavascriptRogin ThomasView Answer on Stackoverflow
Solution 17 - JavascriptDeveloperView Answer on Stackoverflow
Solution 18 - JavascriptAhmed MujtabaView Answer on Stackoverflow