Last updated November 12, 2013. Created by Gábor Hojtsy on October 21, 2013.
Edited by bwinett, mparker17, romainj, yannickoo. Log in to edit this page.

Your module may want to provide functionality at specific URIs of a website or just modify or augment existing functionality. If only existing functionality is modified or extended, you may not need to know about routes. However, if you want to expose content or functionality on your own URIs on a site, routing is an important part of writing your module. This is a quick introduction to routes.

The simplest way to define a route in your module is to include a YAML file named based on your module. Eg. example.routing.yml defining how Drupal will behave when a specific path is encountered:

example.content:
  path: '/example'
  defaults:
    _content: '\Drupal\example\Controller\ExampleController::content'
    _title: 'Hello'
  requirements:
    _permission: 'access content'

This tells Drupal 8 that a route named 'example.content' (named with the module name as prefix) exists and it is bound to the URI '/example' on the site. When that path is accessed, the 'access content' permission is checked on the accessing user and if access is granted, the ExampleController::content method is invoked and a page is displayed with the title 'Hello'.

If you built Drupal 7 modules before, this is pretty similar to how Drupal 7 associated page callbacks to paths in hook_menu(). (However the routing system is not responsible for managing tabs, action links and contextual links).

The second part of creating a page that outputs our content is to put the page controller in place. This could be a PHP 4 style function but best practice in Drupal 8 is to use a controller class. This is in a file named exactly after the controller provided in the routing file, lib/Drupal/example/Controller/ExampleController.php

<?php
/**
* @file
* Contains \Drupal\example\Controller\ExampleController.
*/
namespace Drupal\example\Controller;
/**
* Example page controller.
*/
class ExampleController {
 
/**
   * Generates an example page.
   */
 
public function content() {
    return array(
     
'#markup' => t('Hello!'),
    );
  }
}
?>

Drupal 8 uses a class naming/placement convention called PSR-0. The two things that the class is placed in lib/Drupal/example/Controller/ExampleController.php and is referred to as \Drupal\example\Controller\ExampleController are tightly related.

With only the routing file and the page controller, we made a page available on our site on /example that outputs 'Hello!' on a page titled 'Hello'.

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.