How to create custom page

By nnevill, 20 July, 2023

There are two main ways to create a page in Drupal: via Drupal UI (node page, term page, views, panels (don't use this module!), etc) or programmatically. 

To create a page in code you'll need a module with a module_name.routing.yml file. Given module name is 'snippets', the filename will be snippets.routing.yml:

snippets.example_page:
  path: '/example-page'
  defaults:
    _controller: '\Drupal\snippets\Controller\SnippetsController::examplePage'
    _title: 'Example custom page'
  requirements:
    _permission: 'access content'

Where snippets.example_page is the machine name of the route (page). path is the actual page path. default key describes page and title callbacks for the route. requirements specify the conditions under which the page will be displayed. More about routing system could be found here.

And here is code of PHP controller class:

<?php

namespace Drupal\snippets\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Provides route controller.
 */
class SnippetsController extends ControllerBase {

  /**
   * Returns page content.
   *
   * @return array
   *   Renderable array.
   */
  public function examplePage() {
    return [
      '#markup' => 'Lutsk is the Drupal capital of Ukraine.',
    ];
  }

}

The output will be the following:

Short Description
A simple way to create and custom page (route) in Drupal programmatically.