Rendering menus
The first thing we will look at is how to work with menus programmatically with the view of rendering them in our module. For this, we will work with the default Administration menu that comes with Drupal core and has many links in it, at various levels. Note that the code we write in this section will not be included in the code repository.
Drupal core provides a block, called SystemMenuBlock
, which can be used to render any menu inside a block. However, let's take a look at how we can do this ourselves instead.
The first thing we will need to do is get the MenuLinkTree
service. We can inject it, or, if that's not possible, get it statically via the helper \Drupal
class:
$menu_link_tree = \Drupal::menuTree();
Next, we will need to create a MenuTreeParameters
object so that we can use it to load our menu tree. There are two ways we can do this. We can either create it ourselves and set our own options on it or we can get a default one based on...