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

标签 javascript php phalcon

我正在为我的应用程序使用 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/

相关文章:

javascript - 如何修复浅色主题的闪烁?

php - 将方法的 "Count of Columns"链接到单个查询生成器

javascript - 获取连续第一个值 "On Clicking"并传递给 Controller

php - 在 Phalcon\Mvc\Collection 中使用 mongo 运算符 $and

javascript - 使用 Babel + grunt 与 ES6 一起工作 - 如何转换 require 语句?

javascript - 浏览器中出现错误,提示找不到变量?

javascript - 无法使用 ActiveXObject ('Scripting.FileSystemObject' ) 和 JS 获取子文件夹的名称

php - 中间带有 <div> 标签的 Laravel 表单

javascript - 使用搜索参数创建分页链接

tabs - 如何在 phalcon 中显示选项卡