fgc / menu-bundle
Symfony4 简单而强大的菜单生成器
v3.0.1
2018-11-26 19:19 UTC
Requires
- doctrine/common: *
- symfony/framework-bundle: ~4.1
- twig/twig: ^2.0
README
FGCMenuBundle 是一个简单而强大的 Symfony4 菜单渲染器。
最大的变化是决定移除注解支持。这个特性使得代码处理变得难以管理,并且很难追踪菜单项。因此,将菜单创建集中在配置和事件中。
文档
安装
1. 下载捆绑包
打开命令行,进入您的项目目录,并执行以下命令以下载此捆绑包的最新稳定版本
$ composer require fgc/menu-bundle
此命令要求您全局安装 Composer,如 Composer 文档中的 安装章节 所述。
2. 启用捆绑包
然后,通过在您的项目的 app/AppKernel.php
文件中添加以下行来启用捆绑包
如果您没有 symfony/flex,则需要此步骤。
// config/bundles.php // ... return [ // ... FGC\MenuBundle\FGCMenuBundle::class => ['all' => true], ];
3. 配置捆绑包
捆绑包附带合理的默认配置,如下所示。如果您需要更改这些选项,可以定义这些选项
# config/packages/fgc_menu.yaml fgc_menu: # Menu group name and identifier # default is also the group given if omitted default: # Menu Title Home Page: # each option below is optional # route name for the link to generate route: homepage # route parameters if any. If omitted, an empty array is returned routeOptions: option: value option2: value # icon to be attached to the menu item. Great for dashboards icon: dashboard # order of the items, so inserted Items during events can be integrated smoothly order: 1 # a single ROLE to show only if is_granted() or none to always show This was previously ROLE, and is a # breaking change. granted: IS_ANONYMOUS # This is needed if the granted action needs an object to check against. You may need to dynamically add # the menu item to add objects rather than strings grantedObject: 'User' # to make mult-level menus, menu name to place under this item. children: user
添加动态菜单项
按照 说明 创建一个事件订阅者并监听 DiscoverMenuEvent::NAME
事件。
在这里,您可以实时 $event->addMenuItem(Menu)
。
请确保记住添加组名。
最后
在模板中渲染菜单。
{# ... #} {{ fgc_menu() }} {# ... #}
这将渲染
<li> <a href="/"> Home </a> </li> <li> <a href="/admin/"> Admin Area </a> </li>
并且可以通过额外的参数进行修改。
{{ fgc_menu("Menu Group Name", "template name", (int)depth) }}
模板化菜单
我已经有一些需要用到的模板。
- 默认模板
- bootstrap4
- sb_admin_2
还有更多即将推出,并且可以通过将它们添加到您的 app/Resources 目录中轻松覆盖。
{# templates/bundles/FGCMenuBundle/{template_name}.html.twig #} {% for item in menu %} {% if not item.granted or is_granted(item.granted, item.grantedObject) %} <li> <a href="{{ item.route ? path(item.route, item.routeOptions) : '#' }}"> {% if item.icon %}<i class="fa fa-{{ item.icon }}" ></i>{% endif %} {{ item.name }} </a> {% if item.children and depth %} <ul> {{ fgc_menu(item.children, template, depth) }} </ul> {% endif %} </li> {% endif %} {% endfor %}
结语
在 v2 中,尝试添加缓存,尽管它正确地保存了缓存,但由于变量太多,难以追踪以生成缓存键。我可能会再次尝试,但现在不会。
请随时提交问题,以便可以对其进行改进。