向 CakePHP 中的每个视图添加页面特定的 Javascript [英] Adding page-specific Javascript to each view in CakePHP
问题描述
为了让我的脚本保持可维护性,我将把每个脚本都移动到它们自己的文件中,按控制器和操作进行组织:
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()
中.(是吗?)
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屋!