Using RouteReference¶
Sometimes, when generating links to a resource, you need to modify the default router's behavior.
Example use cases are:
- Language switch links
- Download links
- Passing a Content item instead of a Location (and using its
mainLocationId)
RouteReference represents a route (to a Location object, a declared route, etc.) with its parameters
and can be passed to the Router for generating a link.
RouteReference works like Symfony's ControllerReference for sub-requests.
The advantage of a RouteReference is that its parameters can be modified later,
and then passed to the router (e.g. to generate a link to the same location in several different languages).
Furthermore, the RouteReference generation process can be extended to fit specific needs.
Twig¶
Prototype:
1 | |
routing_resourcecan be any valid resource (route name, Location object, etc.). If omitted (null), the current route will be taken into account.parameters_hashis a hash with arbitrary key/values. It will be passed to the router in the end.
Minimal usage is pretty straightforward:
1 2 3 4 5 6 7 | |
Passing parameters and playing with the RouteReference:
1 2 3 4 5 6 7 8 9 | |
PHP¶
You can generate links based on a RouteReference from PHP too, with the RouteReferenceGenerator service.
Assuming you're in a controller:
1 2 3 4 5 6 7 | |
Extending the RouteReference generation process¶
When generating the route reference, the RouteReferenceGenerator service sends the MVCEvents::ROUTE_REFERENCE_GENERATION (ezpublish.routing.reference_generation) event.
This event can be listened to in order to modify the final route reference
(adding/changing parameters, changing the route name, etc.).
All listeners receive the eZ\Publish\Core\MVC\Symfony\Event\RouteReferenceGenerationEvent object,
which contains the current request object and the route reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
Service declaration (in AcmeExampleBundle/Resources/config/services.yml):
1 2 3 4 5 6 7 8 | |
Example
A real-life implementation example on RouteReference is the LanguageSwitcher (eZ\Publish\Core\MVC\Symfony\EventListener\LanguageSwitchListener).