m4y4-dev/symfony-menu

此包的最新版本(v1.0.2)没有提供许可证信息。

v1.0.2 2018-10-29 16:38 UTC

This package is not auto-updated.

Last update: 2024-09-24 21:27:24 UTC


README

在 symfony 应用中简单使用受限制的菜单

与 composer 一起使用

添加到 composer.json

"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/m4y4-dev/symfony-menu.git"
    }
]

运行

composer require m4y4-dev/symfony-menu:^1.0

添加到您的 symfony 应用

添加到 app/service.yml

(仅在 autoconfigure = false 时需要)

menu_collection:
    class: Symfony\Menu\MenuCollection
    arguments: ["@request_stack", "@security.access_map", "@router", "@security.authorization_checker", "AppBundle/Menu"]

通过将服务添加到 app/config.yml 中的 twig 全局变量,使菜单在 twig 中可用

示例

twig:
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    globals:
        menus: "@menu_collection"

将您的菜单添加到 src/{BundleName}/Menu/

示例

<?php

namespace AppBundle\Menu;

use Symfony\Menu\Menu;

class MainMenu extends Menu
{
    protected $items = [
        [
            'name' => 'Dashboard',
            'icon' => '<i class="icon-home"></i>',
            'path' => 'homepage',
        ],
        [ 
            'name' => 'Link x',
            'icon' => '<i class="icon-diamond"></i>',
            'path' => 'path-to-x',
        ],
        [
            'name' => 'A hidden entry',
            'icon' => '',
            'path' => 'another-path',
            'visible' => false,
        ],
        [
            'name' => 'An entry with submenu',
            'icon' => '<i class="icon-diamond"></i>',
            'path' => '',
            'submenu' => SubmenuMenu::class,
        ],
    ];
}

?>

在 twig 模板中使用如下

{% from 'macro/sidebarMenu.html.twig' import sidebarMenu %}

<ul id="Menu">
    {% for item in menus.MainMenu %}
        {{ sidebarMenu(item, loop) }}
    {% endfor %}
</ul>

宏 sidebarMenu.html.twig 的内容

{% macro sidebarMenu(item, loop) %}{% spaceless %}
    {% from _self import sidebarMenu %}

    {% if isVisible %}
        <li>
            <a{% if item.target|default %} target="{{ item.target }}"{% endif %} href="{% if item.path|default %}{{ url_decode(item.path) }}{% elseif item.link|default %}{{ item.link }}{% endif %}">
                {{ item.icon|raw }}{{ item.name }}
            </a>
        </li>
    {% endif %}
{% endspaceless %}{% endmacro %}

如果您想使用访问控制,只需将您的路由添加到 app/security.yml

示例

access_control:
    - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/, roles: ROLE_USER }