【问题标题】:Detect current page zf2检测当前页面 zf2
【发布时间】:2014-08-17 16:32:26
【问题描述】:

我需要在主布局中知道当前页面是否类似于“模块/控制器”。 因此,例如,如果我在“site.com/module/controller”之类的页面上,则“www/module/application/view/layout/layout.phtml”中的布局必须了解我在那个页面上页面。

你能告诉我,如何应对吗?

谢谢。

【问题讨论】:

    标签: php zend-framework2


    【解决方案1】:

    一个可能的解决方案是将路由参数设置为来自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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-21
      • 2011-07-13
      • 1970-01-01
      • 2012-04-07
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多