Routes
A route links a page address to the code that builds the page. In Drupal routes are not written in PHP — they are described in a YAML file inside the module.
Where routes live
The routes of the blog module are described in the file blog.routing.yml in the root of the module folder. Create it by hand.
The first route
# web/modules/custom/blog/blog.routing.yml
blog.list:
path: '/blog'
defaults:
_controller: '\Drupal\blog\Controller\BlogController::list'
_title: 'Blog'
requirements:
_permission: 'access content'The entry says: for the address /blog, call the list method of the BlogController class. The class does not exist yet — it appears in the next lesson, and until then /blog answers with an error.
What a route consists of
| Key | Meaning |
|---|---|
blog.list | The route name. By convention it starts with the module name |
path | The address. Always starts with a slash |
_controller | The class and the method, separated by two colons |
_title | The title of the page and of the browser tab |
requirements | The conditions under which the page is available |
_permission: 'access content' is the "View published content" permission. By default everyone has it, including anonymous visitors. Access requirements are covered two lessons later.
Several routes
The routes of one module are listed in the same file one after another:
# web/modules/custom/blog/blog.routing.yml
blog.list:
path: '/blog'
defaults:
_controller: '\Drupal\blog\Controller\BlogController::list'
_title: 'Blog'
requirements:
_permission: 'access content'
blog.about:
path: '/blog/about'
defaults:
_controller: '\Drupal\blog\Controller\BlogController::about'
_title: 'About the blog'
requirements:
_permission: 'access content'Each route has its own name and its own controller method. Names must not repeat within the site.
Applying the changes
vendor/bin/drush crDrupal reads route files only when the cache is rebuilt. You can check that the route is registered with a command:
vendor/bin/drush route --path=/blogIt prints the route name, the controller and the access requirements.
Linking to a route
In code and templates a page is referred to by its route name, not by its address:
// in any PHP class
use Drupal\Core\Url;
$url = Url::fromRoute('blog.list')->toString(); // /blogIn a Twig template the path('blog.list') function does the same. If the address in blog.routing.yml changes, every link by name keeps working.
Common mistake
YAML is sensitive to indentation. The path, defaults and requirements keys are indented by two spaces relative to the route name, and their contents by two more. Tabs are not allowed. With an indentation error drush cr reports a broken file or the route simply does not appear — compare the indentation with the example.