In our "Hello World" module, we defined a couple of routes, one of which is the /hello path, which shows our themed salutation component. Let's create a link to that path that goes in the main menu that comes with Drupal core.
As I mentioned, menu links are defined inside a *.links.menu.yml file. So, let's create that file for our module and add our menu link definition in it:
hello_world.hello:
title: 'Hello'
description: 'Get your dynamic salutation.'
route_name: hello_world.hello
menu_name: main
weight: 0
In a typical YAML notation, we have the machine name (in this case, also the plugin ID) hello_world.hello followed by the relevant information below it. These are the most common things you will define for a menu link:
- The title is the menu link title, whereas the description is, by default, set as the title attribute on the resulting link tag
- The route_name indicates the route to be used behind this link
- The menu_name indicates the menu that it should be in; this is the machine name of the menu
- The weight can be used to order links within the menu
An additional common property is parent with which you can indicate another menu link the current one should be a child of. As such, you can build the hierarchy.
Once this is in, you should clear the cache and check out the links in the menu. You'll note that you can edit it, but some things cannot be changed through the UI due to them being defined in code.
Note that links that are created as a result of plugin derivatives, such as the ones created in the UI, have machine names (plugin IDs) in the following format:
main_plugin_id:plugin_derivative_id
The main_plugin_id is the ID of the menu link plugin that is responsible for deriving multiple links, whereas the plugin_derivative_id is the ID given to each individual derivative. For example, in the case of MenuLinkContent entities, the format is like this:
menu_link_content:867c544e-f1f7-43aa-8bf7-22fcb08a4b50
The UUID in the preceding code is actually the UUID of the menu link content entity, which happens to be the plugin derivative ID.