滚动
添加菜单链接
现在,当我们已经为模块的设置页面创建了一个占位符后,让我们来添加一个菜单链接。下面的说明展示了如何在 “管理 > 配置” 页面(http://example.com/admin/config)的 “开发” 部分中,为 hello_world 模块创建一个菜单链接。
在你的模块根目录下创建一个新文件,命名为 hello_world.links.menu.yml,并在其中添加以下内容:
hello_world.admin: title: 'Hello module settings' description: 'example of how to make an admin settings page link' parent: system.admin_config_development route_name: hello_world.content weight: 100
请注意,第一行像我们的 路由文件示例中一样,保留了命名空间。还要注意第 5 行使用了我们的路由名称(我们使用了示例路由文件中第一行的命名空间)。标题和描述将显示在“开发”部分。请注意,parent 行描述了菜单的父级链接。换句话说,菜单链接会被创建在 admin/config/development 下。
这会将 hello_world.content(在此示例中定义在 hello_world.routing.yml)中指定的路径链接到网站后台的“配置”选项卡(URL: /admin/config)的“开发”部分。当然,你需要清除缓存,使更改生效。
清除缓存后,你将在配置页面的“开发”部分找到菜单链接“Hello 模块设置”。点击该链接将调用 hello_world 模块。
额外提示
.links.menu.yml 文件非常灵活。你还可以使用它链接到外部资源或内部路径:
hello_world.admin: title: 'Hello module settings' description: 'example of how to make an admin settings page link' parent: system.admin_config_development url: http://example.com/this-is-some-example weight: 100 hello_world.admin2: title: 'Hello module settings' description: 'example of how to make an admin settings page link' parent: system.admin_config_development url: internal:/some-internal-path
不可编辑:
请注意,当你通过 yml 文件和自定义模块创建菜单链接时,你会得到在用户界面中不可编辑的菜单链接。你只能通过 yml 文件来更改这些链接。它们被认为是模块管理的,而不是管理员自定义的。当你点击菜单项的编辑按钮时,会看到消息:“此链接由模块 XXX 提供。标题和路径不可编辑”。
如果要创建可编辑的菜单链接,你需要这样做:
$my_menu = \Drupal::entityTypeManager()->getStorage('menu_link_content') ->loadByProperties(['menu_name' => 'my-menu-name']); foreach ($my_menu as $menu_item) { $parent_id = $menu_item->getParentId(); if (!empty($parent_id)) { $top_level = $parent_id; break; } } $menu_link = MenuLinkContent::create([ 'title' => 'My menu link title', 'link' => ['uri' => 'internal:/my/path'], 'menu_name' => 'my-menu-name', 'parent' => $top_level, 'expanded' => TRUE, 'weight' => 0, ]); $menu_link->save();