Build dynamic Drupal routes with placeholder parameters
Drupal routing decides which controller serves a URL. A fixed path such as /events is simple, but an Australian events directory often needs distinct pages for Adelaide, Brisbane, Melbourne, Perth and Sydney. A placeholder makes the variable explicit: /events/{city} becomes /events/melbourne while one controller handles every city.
Custom Drupal routing with placeholder parameters keeps those URLs tied to one implementation. The {city} segment is neither a query-string filter nor a page alias; it is a named value captured by the route and supplied to the controller. That distinction affects validation, access checks, caching and editorial links.
Drupal 10 and 11 combine YAML route definitions, controllers, route requirements and parameter converters. A small module can handle a listing or detail page, while larger models may use nodes, taxonomy terms or custom entities. Designing the URL contract first makes later code easier to test and maintain.
The example uses a custom event_finder module and lowercase city slugs. It also accommodates familiar Australian publishing details: local time zones, Australian English, AUD amounts and GST-inclusive prices. Each layer remains separate so developers can change routing logic without disrupting editorial content.
Configure the route in YAML
Create a custom module named event_finder under web/modules/custom/event_finder. Give it an info file and a routing file; the controller can live in src/Controller. A minimal info file is:
name: 'Event Finder'
type: module
description: 'Provides city-based event routes.'
Define the route in event_finder.routing.yml. The route name is unique within Drupal, while {city} is the placeholder name:
event_finder.city_events:
path: '/events/{city}'
defaults:
_controller: '\Drupal\event_finder\Controller\CityEventsController::index'
_title: 'Events'
requirements:
_permission: 'access content'
city: '[a-z0-9-]+'
The leading slash starts the internal path, and the braces mark city as a placeholder. Route names such as event_finder.city_events are stable machine identifiers used by links, redirects and tests. The controller class and method are stored under defaults, while requirements combine a permission with the permitted slug format. Drupal discovers the YAML file when the module is installed; rebuild caches after changing it.
Control placeholder values and access
The city requirement is a regular expression, so only lowercase letters, digits and hyphens reach the controller. Keep accepted values narrow rather than using .+; validation belongs beside the route, although it is not a substitute for access control. Canonical links should use the same lowercase form every time.
A placeholder occupies one path segment and normally cannot contain a slash. Values that should remain optional, such as page two of a listing, are better handled as query parameters unless a real nested URL is required. Drupal route requirements can also restrict the HTTP method and require a permission before any controller code runs.
Missing and unauthorised values should produce predictable responses. Return a 404 response for a city that does not exist and a 403 response when a valid route is forbidden. The generic access content permission in the example keeps the module simple; production sites should normally define a dedicated permission such as access city event listings.
Pass parameters into a controller
Drupal supplies matching route placeholders as controller arguments. The following controller receives $city, loads published event nodes and creates links to them:
<?php
namespace Drupal\event_finder\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
final class CityEventsController extends ControllerBase
{
public function __construct(EntityTypeManagerInterface $entity_type_manager)
{
parent::__construct($entity_type_manager);
}
public function index(string $city): array
{
$storage = $this->entityTypeManager->getStorage('node');
$ids = $storage->getQuery()
->accessCheck(TRUE)
->condition('type', 'event')
->condition('status', 1)
->condition('field_event_city', $city)
->sort('title')
->range(0, 20)
->execute();
$items = [];
foreach ($storage->loadMany($ids) as $event) {
$items[] = [
'#type' => 'link',
'#title' => $event->label(),
'#url' => $event->toUrl(),
];
}
if (!$items) {
throw new NotFoundHttpException();
}
return [
'#type' => 'rendered',
'#title' => $this->t('Events in @city', ['@city' => ucfirst($city)]),
'content' => [
'#type' => 'container',
'#children' => $items,
],
];
}
}
$city arrives as a typed string because the route contains one placeholder. Dependency injection supplies the entity type manager, while accessCheck(TRUE) prevents the node query from bypassing Drupal's node access rules. The controller also limits the result to published event nodes, sorts them by title and turns each node into a canonical link.
Raising NotFoundHttpException produces the normal Drupal 404 page. If the placeholder should resolve to a taxonomy term or node rather than remain text, a parameter converter can return the entity to the controller. Consistent fields are still essential when several routes query the same content; Drupalwoo's reusable content guide explains how configurable fields support predictable event records.
Compare parameter implementation options
There are several ways to model the same information, and the route should reflect how the URL is intended to behave. The following comparison separates simple text capture from entity resolution and optional filtering:
| Approach | Example path | Controller receives | Best suited to | Main caution |
|---|---|---|---|---|
| Raw placeholder | /events/melbourne |
string $city |
Small custom routes | The controller resolves the value |
| Built-in entity parameter | /events/42 |
NodeInterface $event |
Node IDs with entity metadata | Numeric IDs are less descriptive |
| Custom parameter converter | /events/summer-market |
NodeInterface $event |
Readable slugs that resolve to entities | Enforce uniqueness, access and caching |
| Query string | /events?city=melbourne |
Query data | Optional filters and sorting | It is not a path placeholder |
Built-in entity parameters use Drupal's standard parameter conversion and can apply _entity_access: 'view'. A custom converter follows the same tagging mechanism but resolves a slug to a node; it should also run an access check rather than relying on the converter alone. Raw strings remain useful when the value is a modest filter such as a city.
Query strings work well for optional controls such as sort order, but they do not create the nested, crawlable paths often wanted for Australian city campaigns. Pick one canonical representation and redirect duplicates. If a visible slug resolves to a node, preserve the node's canonical URL in links so search engines and visitors receive one stable address.
Recommendations for reliable route workflows in Australia
Always build internal links with Url::fromRoute() rather than concatenating a base URL and path. The route name and an associative array of placeholder values let Drupal handle the base path, installed language and URL generation:
$url = Url::fromRoute('event_finder.city_events', [
'city' => $city,
]);
Dynamic menu links need particular care because the administration interface usually stores one menu item rather than one copy per city. Generate links from published places, or provide a canonical landing page that reaches each city. The case material at SOF Case offers another reference point when comparing practical Drupal patterns with an external implementation. For an Australian events catalogue, map slugs to Adelaide, Brisbane, Melbourne, Perth and Sydney. Store times with an IANA zone such as Australia/Sydney or Australia/Brisbane, because daylight-saving rules differ, display AUD prices clearly as including or excluding GST, and use Australian spelling such as “organisation” and “customisation”.
- Choose stable, lowercase and hyphenated placeholder values that editors can reproduce without seeing the route configuration.
- Give every placeholder an explicit requirement instead of accepting unrestricted text.
- Keep placeholder names consistent between YAML, controller arguments, links and automated tests.
- Use route names and
Url::fromRoute()for internal links rather than hard-coded paths. - Apply access checks at the route, entity and query levels whenever the supplied value resolves to content.
- Treat query parameters as optional filters, not substitutes for meaningful path placeholders.
Test and maintain dynamic routes
Test the route with a known city, an unknown city, an unauthorised user and a valid request carrying extra query data. Confirm that Drupal’s response cache varies by the complete path and that links preserve the expected language and base URL. A functional test can request /events/melbourne, assert a 200 response and check that the page title contains the selected city.
After changing routing.yml, rebuild the container and router caches; otherwise the old definition can remain active. Keep route definitions in version control, deploy them with the module, and record any changed public path in the site’s redirect configuration. Renaming a placeholder is safer than renaming its route name when existing links and modules depend on it.
A route ultimately behaves as a small public contract: it names a URL shape, validates an input, applies access policy and delegates rendering. With explicit requirements and deliberate converter decisions, the same mechanism supports event pages, member profiles and service-area listings without turning every variable path into separate custom code.