zend 2:尝试在我的视图助手中使用Zend \ Navigation

时间:2014-03-20 21:16:37

标签: dependency-injection zend-framework2

我正在尝试使用Zend \ Navigation在视图帮助器中从模板创建菜单栏。

我越来越近了,用我现在的代码编辑了这个帖子。

以下是视图助手:

<?php
namespace Helpdesk\View\Helper;

use Zend\View\Helper\AbstractHelper;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class Navbar extends AbstractHelper implements ServiceLocatorAwareInterface {

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
        $this->serviceLocator = $serviceLocator;    
        return $this;  
    }

    public function getServiceLocator() {
        return $this->serviceLocator;
    }

    public function __invoke() {
        $partial = array('helpdesk/helpdesk/subNavTest.phtml','default');
        $navigation = $this->getServiceLocator()->get('navigation');
        $navigation->menu()->setPartial($partial);
        return $navigation->menu()->render();
    }
}

我在module.config.php中配置了导航,如下所示:

'view_helpers' => array(
    'invokables' => array(
        'navbar' => 'Helpdesk\View\Helper\Navbar',
    ),
),

'navigation' => array(
    'default' => array(
        array(
            'label' => 'One',
            'route' => 'link',
        ),
        array(
            'label' => 'Two',
            'route' => 'link',
        ),
        array(
            'label' => 'Three',
            'route' => 'link',
        ), ...

但是当我在我的视图中显示它时,<?php echo $this->navbar(); ?>它只显示部分模板 ,而不是 来自module.config.php的导航配置。< / p>

如果我在我的视图中执行以下操作,则可以使用我设置的配置显示:

<?php $partial = array('helpdesk/helpdesk/subNavTest.phtml','default') ?>
<?php $this->navigation('navigation')->menu()->setPartial($partial) ?>
<?php echo $this->navigation('navigation')->menu()->render() ?>

为什么我的视图助手没有拉入导航配置?

1 个答案:

答案 0 :(得分:2)

  

如果我在我的视图中执行以下操作,则可以使用我设置的配置显示:

是的,那是因为在您的视图中(有效的代码),您告诉导航助手在此行使用名为navigation的菜单容器......

<?php $this->navigation('navigation')->menu()->setPartial($partial) ?>
                         ^^^^^^^^^^- This is the menu container

navbar帮助器中,您没有指定菜单容器。如果您尚未在此时使用导航助手,则它没有菜单,并创建一个空菜单。

您有两个选择,要么在调用帮助程序之前告诉导航助手要使用哪个容器

// set the menu 
<$php $this->navigation('navigation'); ?>
// render helper
<?php echo $this->navbar(); ?>

或者让你的助手接受__invoke方法中可以传递给帮助者的参数

public function __invoke($container) {
    $partial = array('helpdesk/helpdesk/subNavTest.phtml','default');
    $navigation = $this->getServiceLocator()->get('navigation');
    // tell navigation which container to use 
    $navigation($container)->menu()->setPartial($partial);
    return $navigation->menu()->render();
}

并在您的视图中将其称为

<?php echo $this->navbar('navigation'); ?>