向CakePHP中的每个视图添加特定于页面的Javascript [英] Adding page-specific Javascript to each view in CakePHP

查看:98
本文介绍了向CakePHP中的每个视图添加特定于页面的Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了保持我的脚本可维护性,我将把每个文件移动到自己的文件中,由控制器和操作组织:

In an attempt to keep my scripts maintainable, I'm going to move each into their own file, organised by controller and action:

// scripts which only apply to /views/posts/add.ctp
/app/webroot/js/page/posts/add.js

// scripts which only apply to /view/users/index.ctp
/app/webroot/js/page/users/index.js

这很酷,但是我想让这些由控制器自动添加,因为它显然知道控制器和操作的名称。

That's all cool, however I'd like for these to be automatically added by the Controller, since it obviously knows the name of both the controller and action.

我认为最好的地方是 AppController :: beforeRender()。 (yes?)

I figure the best place for this is in AppController::beforeRender(). (yes?)

唯一的问题是我不知道如何将它添加到 $ scripts_for_layout 变量。我认为得到一个引用 javascript 帮助器对象将工作,但我不能从控制器中找到它!

The only problem is that I don't know how to actually add this into the $scripts_for_layout variable. I thought that getting a reference to the javascript helper object would work, but I can't find it from the controller!

class AppController extends Controller {
    var $helpers = array("javascript", "html", "form");

    function beforeRender() {
        // ???
    }
}


推荐答案

容易在 default.ctp 布局文件中进行:

Very easy to do in your default.ctp layout file:

自动包含 .css 每个控制器和/或控制器/操作的文件(因为我有这个,容易适应 .js 文件):

An example to automatically include .css files per controller and/or controller/action (because I had this lying around, easily adaptable to .js files):

<head>
...
<?php
    if (is_file(WWW_ROOT . 'css' . DS . $this->params['controller'] . '.css')) {
        echo $html->css($this->params['controller']);
    }
    if (is_file(WWW_ROOT . 'css' . DS . $this->params['controller'] . DS . $this->params['action'] . '.css')) {
        echo $html->css($this->params['controller'] . '/' . $this->params['action']);
    }
?>
...
</head>

这篇关于向CakePHP中的每个视图添加特定于页面的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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