Best way of global registering ClientScript?

拟墨画扇 提交于 2020-01-01 03:34:05

问题


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...


回答1:


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




回答2:


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();
}



回答3:


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.




回答4:


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/



来源:https://stackoverflow.com/questions/10025189/best-way-of-global-registering-clientscript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!