This time it’s Twig, but it’s about Symfony’s Twig extension.
Among them, this time I would like to introduce how to get the route path and how to make it.
Official:Twig Extensions Defined by Symfony
Get route names and parameters in Twig
A Symfony extension that allows you to use a variable called app
as a global variable.
Information such as routes is also stored in the app.
Get the route name
For example, suppose you have the following route setting page. (Hereafter, this page setting will be used)
// Sample Root (Controller) /** * test product page. * * @Route( * "/product/{id}/{type}", * name="product_main", methods={"GET"}, * defaults={"type" = 1} * ) ...
The method to get the route name and parameters is as follows.
// Global Variables // Route Name app.request.attributes.get('_route') // dump Variables "product_main" // Route Params app.request.attributes.get('_route_params') // dump Variables array:2 [ "id" => 13, "type" => 1 ]
Generate path with Twig
How to use path
in Symfony’s Twig Extensions.
// Basic relative URL path('route_name') // Basic absolute URL url('route_name')
Basically, as mentioned above, you can generate relative URL / absolute URL from the root name. You can also generate a URL with parameters like this sample product_main
. The parameter must be set if default is not set.
// product_main page sample // current page path(app.request.attributes.get('_route'), { 'id': app.request.attributes.get('_route_params').id}) // other id path(app.request.attributes.get('_route'), { 'id': 11})
When specifying multiple parameters.
path(app.request.attributes.get('_route'), { 'id': 11, 'type': 2})
It’s easy, but it was an introduction to how to get the current route information and generate a URL.