I'm stumped on how to achieve this in Drupal 8 due to the removal of menu related functions. What I would like to do is check whether a menu link points to a node of content type File, and then alter the link path to point to a File field value on node (so that the menu link points to the file itself). I just need help getting to the point where I have both the path/route and the node object. I have tried to do this in menu--main.html.twig
, where I can get the node id for each menu item. However there does not seem to be a way to load a node object through Twig and even if there were, I doubt this is the correct way to go about this.
I have found tutorials pointing me to implement alterRoutes()
, for example:
public function alterRoutes(RouteCollection $collection, $provider) {
// Find the route we want to alter
$route = $collection->get('example.route.name');
// Make a change to the path.
$route->setPath('/my/new/path');
// Re-add the collection to override the existing route.
$collection->add('example.route.name', $route);
}
This doesn't seem helpful because I do not want to alter the route to the node whenever it is visited. I only want to alter the route when it is visited from the menu.