Routes can accept dynamic arguments that can be passed to the route controller's method. Placeholder elements can be defined in the route using curly brackets in the URL that denote dynamic values.
The following example code shows what a route might look like:
mymodule.cats:
path: '/cat/{name}'
defaults:
_controller: '\Drupal\mymodule\Controller\MyPageController::cats'
requirements:
_permission: 'access content'
This route specifies the /cat/{name} path. The {name} placeholder will accept dynamic values and pass them to the controller's method:
class MyPageController {
// ...
public function cats($name) {
return [
'#markup' => t('My cats name is: @name', [
'@name' => $name,
]),
];
}
}
This method accepts the name variable from the route and substitutes it into the render array to display it as a text.
Drupal's routing system provides a method of upcasting a variable into a loaded object. In Drupal, upcasting is the process of taking a route parameter and converting it into a richer piece of data. This includes taking an entity ID and providing the loaded entity to the system. There are a set of parameter converter classes under the \Drupal\Core\ParamConverter namespace. The EntityConverter class will read options defined in the route and replace a placeholder value with a loaded entity object.
If we have an entity type called cat, we can turn the name placeholder into a method that will be provided with the loaded cat object in our controller's method:
mymodule.cats:
path: '/cat/{name}'
defaults:
_controller: '\Drupal\mymodule\Controller\MyPageController::cats'
requirements:
_permission: 'access content'
options:
parameters:
name:
type: entity:cat