注册您自己的提供器
注册您自己的菜单提供器允许您使用您自己的数据来填充菜单,这些数据可以通过您的代码访问。例如,它可以遍历 PHPCR 仓库并创建相应的菜单元素。
首先在您的扩展包的 Provider 目录下创建您的 Provider 类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
namespace App\Provider;
use Knp\Menu\FactoryInterface;
use Knp\Menu\Provider\MenuProviderInterface;
class CustomMenuProvider implements MenuProviderInterface
{
/**
* @var FactoryInterface
*/
protected $factory = null;
/**
* @param FactoryInterface $factory the menu factory used to create the menu item
*/
public function __construct(FactoryInterface $factory)
{
$this->factory = $factory;
}
/**
* Retrieves a menu by its name
*
* @param string $name
* @param array $options
* @return \Knp\Menu\ItemInterface
* @throws \InvalidArgumentException if the menu does not exists
*/
public function get($name, array $options = [])
{
if ('demo' == $name) { //several menu could call this provider
$menu = /* construct / get a \Knp\Menu\NodeInterface */;
if ($menu === null) {
throw new \InvalidArgumentException(sprintf('The menu "%s" is not defined.', $name));
}
/*
* Populate your menu here
*/
$menuItem = $this->factory->createFromNode($menu);
return $menuItem;
}
}
/**
* Checks whether a menu exists in this provider
*
* @param string $name
* @param array $options
* @return bool
*/
public function has($name, array $options = [])
{
$menu = /* find the menu called $name */;
return $menu !== null;
}
}
然后,配置链接到这个新提供器的服务。
1 2 3 4 5 6 7 8 9 10
# config/services.yaml or app/config/services.yml
services:
app.menu_provider:
class: App\Provider\CustomMenuProvider
arguments:
- '@knp_menu.factory'
tags:
- { name: knp_menu.provider }
# ...
最后,要生成菜单,例如在 twig 模板中输入
1
{{ knp_menu_render('demo') }}
Symfony CMF MenuBundle 提供了一个完整的可工作示例。
这项工作,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。