gpt4 book ai didi

javascript - phalcon php 根据 Controller 和操作名称包含 js

转载 作者:行者123 更新时间:2023-11-28 01:21:46 24 4
gpt4 key购买 nike

我正在为我的应用程序使用 phalcon php 框架。该应用程序经常使用 JavaScript 进行交互。

是否有一个类/服务也会根据名称包含 js Controller ,否则如果找不到,则包含“主”javascript 文件?

例如我请求的网址: http://www.mysite.com/search/keyword

因此 phalcon 将使用包含参数的 indexAction 来执行 searchController。从indexAction函数返回的数据将被传递到 View 。

该 View 还将包含 js/search/index.js

(也许还包括一个 css 文件 css/search/index.css!?)

js 有这种类型的层次结构功能吗?

最佳答案

没有任何开箱即用的东西,但这相对容易实现。您可以在基本 Controller 中实现该逻辑,大致如下:

abstract class AbstractController extends \Phalcon\Mvc\Controller
{
public function afterExecuteRoute()
{

// Don't want to add assets if the action gets forwarded.

if (!$this->dispatcher->isFinished()) {
return;
}

$controllerName = $this->dispatcher->getControllerName();
$actionName = $this->dispatcher->getActionName();
$path = 'js/' . $controllerName. '/' . $actionName . '.js';

// Defining APPLICATION_PATH global constant is one way of pointing to the root of your application.
// This can be done in your config or index. Alternatively you could add config to your DI and do
// something like DI::getDefault()->getShared('config')->applicationPath.

if (file_exists(APPLICATION_PATH . '/public/' . $path)) {
$this->assets->addJs($path);
} else {
$this->assets->addJs('js/main.js');
}
}
}

并在 View 中output them as usual :

<html>
<head>
<title>Some amazing website</title>
<?php $this->assets->outputCss() ?>
</head>
<body>

<!-- ... -->

<?php $this->assets->outputJs() ?>
</body>
<html>

看看controller events ,它们在这种时候真的很方便。

已更新

另一种可能的方法是通过 View 选择逻辑来加强 js 的选择。该 View 将检查 views/controller/action.voltviews/layouts/controller.volt 等,详细了解 hierarchical rendering 。通过将 js 层次结构与实际 View 层次结构相匹配,这将有助于使事情变得更加整洁。如何实现这取决于您,但最好将其全部保留在同一个 afterExecuteRoute 处理程序中。

关于javascript - phalcon php 根据 Controller 和操作名称包含 js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23188164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com