Russell Seymour Russell Seymour - 1 month ago 5
PHP Question

How can I set the route parameter name using a variable in Twig?

I am trying to use the

url
Twig function with Silex to generate a route, but when I use the variable name that I have passed to the template it generates a warning that I have not supplied the parameter.

This is the array I am passing to the template:

[
"total_pages" => $pages,
"current_page" => $page,
"route_name" => "gallery_album",
"route_parameter" => "groupname",
"route_value" => $groupname
]


And in the template I am trying to use:

{{ url(route_name, {route_parameter: route_value, 'page': page} ) }}


(The page variable value is worked out in the template)

This is part of a pagination template that I am building so I need the parameter to be a variable so it can be applied to different pages. This is the error I get when I run this:

enter image description here

I feel this is something that is very simple, I am just missing something fundamental.

Answer

It thinks that route_parameter is a string key name and not a variable:

You can do for example:

{% set params = {'page': page, (route_parameter): route_value } %}
{{ url(route_name, params) }}