[英]Detect current page zf2
I need to know in the main layout, if current page is like "module/controller". 我需要在主布局中知道当前页面是否类似于“模块/控制器”。 So, for instance, if I am on the page like "site.com/module/controller", the layout which is in "www/module/application/view/layout/layout.phtml" has to understand that I am on that page. 因此,例如,如果我在“ site.com/module/controller”之类的页面上,则“ www / module / application / view / layout / layout.phtml”中的布局必须了解我在该页面上页。
Could you tell me please, how to cope with it? 你能告诉我如何处理吗?
Thank you. 谢谢。
A possible solution for that is to set the route parameters as layout variables from your Module.php
. 一个可能的解决方案是将路径参数设置为Module.php
布局变量。
Assuming you have a route configuration which looks like this : 假设您具有如下所示的路由配置:
'route' => '/[:module[/:controller[/:action]]]
You can use the following code : 您可以使用以下代码:
In your Module.php
file : 在您的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');
}
Note : If you haven't module
in the route parameter you can get it as follows : 注意:如果没有在route参数中添加module
,则可以按以下方式获取它:
$controllerClass = get_class($controller);
$moduleName = substr($controllerClass, 0, strpos($controllerClass, '\\'));
$controller->layout()->modulename = $moduleName;
In your layout : 在您的布局中:
Now you can access the variables in your layout just like this : 现在,您可以像这样访问布局中的变量:
Current page :<?php echo $this->modulename.'/'.$this->controllername.'/'.$this->actionname; ?>
Example : 范例:
Page : site.com/application/index/home
页面: site.com/application/index/home
Output : Current page : Application/index/home
输出: Current page : Application/index/home
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.