call to undefined method yii::app()
yii2 register css
yii2 get base url
yii2 get asset url
.css files in a specific view.
Something like this:
<?php $baseUrl = Yii::app()->baseUrl; $cs = Yii::app()->getClientScript(); $cs->registerScriptFile($baseUrl.'/js/yourscript.js'); $cs->registerCssFile($baseUrl.'/css/yourcss.css'); ?>
You can do so by adding
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. ), ), ), ),
In the view, add the following:
<?php $cs = Yii::app()->getClientScript(); $cs->registerScriptFile('/js/yourscript.js', CClientScript::POS_END); $cs->registerCssFile('/css/yourcss.css'); ?>
- should I call this from the controller of from the view?
- You should call this from a view
- @user1077220 It makes no difference.
- CSS and JS registrations are relate to view. So more logically to call it from a view.
- This should be added once per page (no matter in which view you will add above snippet)
- you can use this way: Yii::app()->clientScript->registerCoreScript('bootstrap');
- @Christian this is not a forum, and you are encouraged to add on to questions if you are contributing new AND useful information.
- @Truongnq If I place this block
$baseUrl = Yii::app()->baseUrl; $cs = Yii::app()->getClientScript(); $cs->registerScriptFile($baseUrl.'/js/yourscript.js'); $cs->registerCssFile($baseUrl.'/css/yourcss.css');in the Controller, where do I assign
$csafter? Moreover, in my
actionViewin my Controller I have this line
$this -> render('view', array('model' => $this -> loadModel($id), ));, should I place it here?
- am stuck on the best approach when using partial render. Am having my JS Files conflicting. Which is the best approach for this
- Nice Solution. i will try it in my Application