全局注册 ClientScript 的最佳方式? [英] Best way of global registering ClientScript?

查看:28
本文介绍了全局注册 ClientScript 的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想全局注册用户脚本,以便在整个站点上可用.现在我插入控制器中的每个动作:

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

推荐答案

如果您希望在您的项目中使用主题,我会将一些 css 和脚本放在布局文件 (views/layouts/my-layout-file.php).因为如果您更改主题,您将使用另一个 css,有时可能还会使用另一个脚本,所以您不想将它们混合在一起.

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.

但是一些主要的 css 和 scipts,没有改变跨主题,我会放在主要的 Controller (protected/components/Controller.php)而所有其他控制器(/protected/controllers/)将扩展此类控制器

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.

编辑:@realtebo(在评论中)指出使用beforeRender' 不是 'beforeAction'.

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

查看更多:了解视图渲染流程

这篇关于全局注册 ClientScript 的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆