Zend Framework 2:在视图中获取匹配的路由 [英] Zend Framework 2: get matched route in view

查看:79
本文介绍了Zend Framework 2:在视图中获取匹配的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在通过大致基于框架应用程序开发一个小型MVC应用程序来学习ZF2.现在,我正在尝试根据匹配的路线隐藏一些固定的HTML元素:仅作为示例,我不希望在登录阶段显示主菜单.

I'm currently learning ZF2 by developing a small MVC application roughly based on the skeleton app. Right now I'm trying to hide some fixed HTML elements based on the route matched: just as an example, I don't want the main menu to show during the login phase.

我可以通过将切换参数作为控制器动作的返回值传递来轻松地做到这一点,但是感觉不对,所以我只想检查布局中匹配的路由并相应地组成布局.

I can do that easily by passing toggle parameters as return values from the controller actions, but it doesn't feel right, so I'd like to just check the matched route from the layout and compose the layout accordingly.

问题是,我不知道如何在模板中获取匹配的路由.这可能吗?还有其他解决方案可以避免在控制器中添加布局逻辑吗?

Problem is, I don't know how to get the matched route in the template. Is this possible? Are there other solutions to avoid adding layout logic into controllers?

编辑,经过科学怪人的出色工作,我终于找到了解决方案.我喜欢使用帮助器的想法,因此我只是尝试通过主模块中的boostrap函数向其传递Application对象:

Edit after some good Frankenstein work, I was able to find a solution for this. I like the idea of using a helper, so I just tried to pass it the Application object, from the boostrap function in the main module:

$app = $e->getApplication();
$serviceManager = $app->getServiceManager();
....
$serviceManager->get('viewhelpermanager')->setFactory('getRoute', function($sm) use ($app) {
    return new Helper\GetRoute($app);
});

和辅助功能:

use Zend\View\Helper\AbstractHelper;

class GetRoute extends AbstractHelper {
    private $sm;

    public function __construct($app) {
        $this->sm = $app->getServiceManager();
    }

    public function echoRoute() {
        $router = $this->sm->get('router');
        $request = $this->sm->get('request');

        $routeMatch = $router->match($request);
        if (!is_null($routeMatch))
            echo $routeMatch->getMatchedRouteName();
    }
}

也许有一种更清洁,更ZF2ish的方式可以做到这一点...

perhaps there's a cleaner, more ZF2ish way to do this...

推荐答案

另一个没有新匹配项的解决方案

Another solution without a new match

$routeMatch = $serviceLocator->get('Application')->getMvcEvent()->getRouteMatch();

echo $routeMatch->getMatchedRouteName();

这篇关于Zend Framework 2:在视图中获取匹配的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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