Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

To generate a dynamic routes, we start off with the route_callbacks method.

To begin, you just add the method in your routing.yml with the callback to your class and method:

  - '\Drupal\mymodule\Routing\MyModuleRoutes::routes'


Then you just need to make a Routing class and slap in your logic. Basically you are creating the YAML version of the typical route in PHP in the routes method.

in this class also I Inject config.factory service to get dynamic params from config form.


namespace Drupal\mymodule\Routing;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;

 * Class MyModuleRoutes
 * @package Drupal\mymodule\Routing
class MyModuleRoutes implements ContainerInjectionInterface {

   * @var \Drupal\Core\Config\ImmutableConfig
  protected $config;

   * MyModuleRoutes constructor.
   * @param ConfigFactoryInterface $config_factory
  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->config = $config_factory->get('mymodule.settings');

   * {@inheritdoc}
  public static function create(ContainerInterface $container) {
    return new static(

   * {@inheritdoc}
  public function routes()
    $routes = [];
    $pid = 1;
//    $path = '/example';
    $path = $this->config->get('path_page');

    $routes['mymodule.page_' . $pid] = new Route(
        '_controller' => '\Drupal\mymodule\Controller\MyModuleController::index',
        '_title' => 'Hello'
        '_permission' => 'access content',

    return $routes;



As you can see this is basically adding another layer between the routing.yml and the Controller. Here is what our Controller looks like this:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyModuleController extends ControllerBase {

   * @return string[]
  public function index() {
    return [
      '#markup' => 'Hello world ?',



to read more about that topic see this link.


Submitted by lakshmi (not verified) on Sat, 02/12/2022 - 17:29 Permalink

uncomment $path, otherwise, we are getting an error
Add new comment

Restricted HTML

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

I am a senior web developer, I have experience in planning and developing large scale dynamic web applications especially in Drupal and Laravel.

Web Posts


Page Facebook