Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way of global registering ClientScript?

Tags:

yii

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

like image 598
Nick_NY Avatar asked Dec 27 '22 03:12

Nick_NY


2 Answers

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

like image 188
briiC Avatar answered Jan 18 '23 23:01

briiC


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();
}
like image 37
Onkar Janwa Avatar answered Jan 18 '23 22:01

Onkar Janwa