Blogs

EMAIL: info@example.com

#! code: Drupal 9: Loading All Routes From A Module

When creating Drupal modules I like to keep the hard coded components to a minimum. This helps when changing parts of the module in the future as hard coded links and other elements will require manual intervention and slow down maintenance. Sometimes, though, this isn’t an option as you just need to have a few routes in your *.routing.yml file that point to controllers or forms within your module.

I had a situation today where I was looking to load all of the routes that are contained in a module. I could then construct a page of links that would handily point to different parts of the module or feed those links into a sitemap. This meant that I wouldn’t need to hard code this list into a controller, I just needed to load all the routes and print that list out instead. Especially handy if I ever added or removed a route as that would mean that list would update without me having to do it manually.

Using Core Services

As it happens, Drupal doesn’t have a service that allows you to search for routes that have a similar signature or structure. There are a couple of things that look like they might work, but end up not being what I was looking for. I’ll go through them here for completeness.

The first option I found was the getRouteByName() method from the router.route_provider service. This does a one-to-one match of a given route against the routes you have within a site. Because the searching is done as lookup on an array of routes the method doesn’t accept wildcard searching.

The following example would only retrieve a single route.

Read more.


Go to Source
Author: