Best way of global registering ClientScript?

2019-03-21 13:04发布

I want to register user script globally, to be available all over the site. Now I insert in every action in my controllers:

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/script.js');

But really I understand that it's not good way...

标签: yii
4条回答
何必那么认真
2楼-- · 2019-03-21 13:56

The best way to register global js and css files I think is registering them in beforeRender() method (not in beforeAction() - because if you render json or xml this may destroy your structure) of some BaseController.

查看更多
forever°为你锁心
3楼-- · 2019-03-21 13:58

You can do this in this way : initiate init function in base controller class having path protected/components/controller.php

public function init()
{
  Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/script.js'); 
  parent::init();
}
查看更多
劳资没心,怎么记你
4楼-- · 2019-03-21 14:07

U can do like this: 1. create private attribute $_assetsUrl; 2. then in the module or controller

public function getAssetsUrl()
{
    if ($this->_assetsUrl===null)
    {
        $assetsPath = $this->basePath.DIRECTORY_SEPARATOR.'assets';
        $this->_assetsUrl = Yii::app()->assetManager->publish($assetsPath,false,-1,YII_DEBUG);
        if (Yii::app()->theme!==null && is_dir($assetsPath.DIRECTORY_SEPARATOR.Yii::app()->theme->name))
            $this->_assetsUrl .= DIRECTORY_SEPARATOR.Yii::app()->theme->name;
    }
    return $this->_assetsUrl;
}

Hope this was useful, see also this link http://www.yiiframework.com/wiki/148/understanding-assets/

查看更多
淡お忘
5楼-- · 2019-03-21 14:11

If you are looking forward to use themes in your project, i would put some css and scripts in layout file (views/layouts/my-layout-file.php). Because if you changing theme you will be using another css and maybe sometimes another scripts, so you would not want to mix it together.

But some main css and scipts, that didn't change accross themes, i would put in main Controller (protected/components/Controller.php) And all other controllers (/protected/controllers/) would extend this class Controller

class PageController extends Controller {

And so if all your controllers using on parent class, you can edit just parent class and add something like this

public function beforeRender( $view ) {
    ...
    Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/script.js');
    ...
    return true;
}

And all your actions will be now using same script.

EDIT: @realtebo (in comments) pointed out to use 'beforeRender' not 'beforeAction'.

See more: Understanding the view rendering flow

查看更多
登录 后发表回答