【发布时间】:2014-08-17 16:32:26
【问题描述】:
我需要在主布局中知道当前页面是否类似于“模块/控制器”。 因此,例如,如果我在“site.com/module/controller”之类的页面上,则“www/module/application/view/layout/layout.phtml”中的布局必须了解我在那个页面上页面。
你能告诉我,如何应对吗?
谢谢。
【问题讨论】:
标签: php zend-framework2
我需要在主布局中知道当前页面是否类似于“模块/控制器”。 因此,例如,如果我在“site.com/module/controller”之类的页面上,则“www/module/application/view/layout/layout.phtml”中的布局必须了解我在那个页面上页面。
你能告诉我,如何应对吗?
谢谢。
【问题讨论】:
标签: php zend-framework2
一个可能的解决方案是将路由参数设置为来自Module.php 的布局变量。
假设您的路由配置如下所示:
'route' => '/[:module[/:controller[/:action]]]
您可以使用以下代码:
在您的Module.php 文件中:
public function onBootstrap($e)
{
//....
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach('dispatch', array($this, 'initView' ));
//....
}
public function initView(MvcEvent $e)
{
$controller = $e->getTarget();
$route = $controller->getEvent()->getRouteMatch();
//set variables into the layout
$controller->layout()->modulename = $route->getParam('module');
$controller->layout()->controllername = $route->getParam('controller');
$controller->layout()->actionname= $route->getParam('action');
}
注意:如果路由参数中没有module,可以如下获取:
$controllerClass = get_class($controller);
$moduleName = substr($controllerClass, 0, strpos($controllerClass, '\\'));
$controller->layout()->modulename = $moduleName;
在您的布局中:
现在您可以像这样访问布局中的变量:
Current page :<?php echo $this->modulename.'/'.$this->controllername.'/'.$this->actionname; ?>
示例:
页面:site.com/application/index/home
输出:Current page : Application/index/home
【讨论】: