routes - 在 ViewHelper 中访问路由器以匹配路由或 child_routes

标签 routes zend-framework2 view-helpers

我遇到了一个问题,目前我对框架的功能不了解。我想设置一个 ViewHelper ,它根据我所在的站点返回输出。如果我匹配两个特定的routeschild_routes,我希望ViewHelper根据该路由输出链接列表。如果我不在那些匹配的路线上,我不想输出任何内容。

设置 ViewHelper 非常简单,现在我的 ViewHelper 看起来像这样:

'factories' => array(
    'myViewHelper' => function($sm) {
        $service = $sm->getServiceLocator()->get('some-doctrine-entity');
        return new \Mynamespace\View\Helper\ViewHelper($service);
    }
)

输出是一个类似的链接列表

$this->url('someLink', array('id', $service->getId());

现在我的问题是 someLink 部分需要是可变的。它应该是 foobarfoobar 都可以有 child_routesfoo/index, foo/details, foo/etc 我需要匹配所有这些。

所以我的问题是如何写这个

$currentRoute = somehowGetTheCurrentRoute();
if ($currentRoute matching `foo` or `foo/child_routes`
  or is matching `bar` or `bar/child_routes`) {
    echo "im happy";
}

最佳答案

您可以在 View 助手上定义一个方法,它假设您有权访问服务管理器。以下是解决您的问题的方法:

//$sm is the service manager

$router=$sm->get('Router');
$request=$sm->get('Request');
$routeMatch=$router->match($request);

//get an array of the route params and their values
$routeparams=$routeMatch->getParams();

//get the matched route name
$routename=$routeMatch->getMatchedRouteName();

//The previous parameters can be injected directly into the url plugin call
//$this->url($routename,$routeparams)

//the full path can also be obtained from the router
//(you can test it within a controller)
$path=$router->assemble($routeparams,$options);

关于routes - 在 ViewHelper 中访问路由器以匹配路由或 child_routes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14047043/

相关文章:

c - 我们如何在网格中找到两条权重最大的路线?

node.js - Mongoose 模型中的元排序

php - Zend Framework 2 - 使用来自 Controller 插件的值设置布局变量

php - 如何从MySql在ZF2中显示utf8字符

asp.net-mvc-4 - 是否有用于可折叠(多级)Bootstrap 3 菜单的简单 MVC4 html 帮助程序?

javascript - 在 Ember 中命名和声明嵌套 CRUD 页面的正确方法

authentication - 有没有一种在 Actix 路由级别实现身份验证/授权检查的好方法?

zend-framework2 - zf2 在两个不同的数据库之间建立连接

ruby-on-rails-4 - 基于未定义方法的模板错误 'custom_helper'

asp.net-mvc - 在 Helper 错误 : The name 'TempData' does not exist in the current context 中使用 TempData