How to create Dynamic Routes

I have been trying to create dynamic routes by using RouteSubscriberBase class.

I know we can create dynamic routes by using slug parameter in the URL. Similar to this method ( https://befused.com/drupal/dynamic-route ).

But I want is dynamic Routes not URLs.Similar to this method ( https://www.previousnext.com.au/blog/dynamic-routes-drupal-8-routesubscriber )

Here is the code I have written so far but I cant get whats missing in the code.

When I try to access http://example.com/custom-module/dynamic-routes/ it is available but when I try to access http://example.com/custom-module/dynamic-routes/tents I am getting Page not found Error.

I have Cleared cache before accessing the new URL.

DynamicRoutesAlter.php

<?php  namespace Drupal\custom_module\Routing;  use Drupal\Core\Routing\RouteSubscriberBase; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection;  /**  * DynamicRoutesAlter Class.  */ class DynamicRoutesAlter extends RouteSubscriberBase {    /**    * {@inheritdoc}    */   public function alterRoutes(RouteCollection $  collection) {     $  products = ['cooking_gear' => 'Cooking Gear', 'tents' => 'Tents' , 'sleeping_bags' => 'Sleeping Bags','rope' => 'Rope', 'safety' => 'Safety','packs' => 'Packs'];       foreach ($  products as $  key => $  value) {        $  url = preg_replace('_', '-', $  key);        $  route = new Route(         // The url path to match.         '/custom-module/dynamic-routes/' . $  url,         // The defaults (see the custom_module.dynamic_routes for structure)         [           '_title' => $  value,           '_controller' => '\Drupal\custom_module\Controller\DynamicRoutesController::productType',           'type' => $  key,         ],         // The requirements.         [           '_permission' => 'create ' . $  value,         ]       );        // Add our route to the collection with a unique key.       $  collection->add('custom_module.dynamic_routes'.{$  key}, $  route);      }   }  } 

custom_module.services.yml

  custom_module.dynamic_routes:     class: Drupal\custom_module\Routing\DynamicRoutesAlter     tags:       - { name: event_subscriber }     

custom_module.routing.yml

custom_module.dynamic_routes:   path: '/custom-module/dynamic-routes'   defaults:     _title: 'Dynamic Routes'     _controller: '\Drupal\custom_module\Controller\DynamicRoutesController::productType'   requirements:     _permission: 'access content'       

DynamicRoutesController.php

  /**    * {@inheritdoc}    */   public function productType() {      $  build['results'] = [       '#markup' => $  this->t('Controller to get Products List.'),     ];      return $  build;   }