Skip to content

Instantly share code, notes, and snippets.

@aklump
Created May 30, 2025 00:00
Show Gist options
  • Save aklump/657bc50387cc82400b92dcbe4ee7fd17 to your computer and use it in GitHub Desktop.
Save aklump/657bc50387cc82400b92dcbe4ee7fd17 to your computer and use it in GitHub Desktop.
Generate a URL template from a Drupal route name (with optional/partial parameter replacement).
<?php
namespace Drupal\commons_core\Helper;
use http\Exception\InvalidArgumentException;
class GetUrlTemplateByRouteName {
/**
* Generate a URL template from a route.
*
* @param string $route_name , e.g. 'my_module.foo'
* @param array $route_parameters Optional parameters if you wish to
* subsitute tokens with real values. Otherwise, the tokens remain in the
* response.
*
* @return string The URL of the route with tokens (unless passed in
* $route_parameters, in which case those are replaced.), e.g.
* '/my-module/{uid}/foo'
*/
public function __invoke(string $route_name, array $route_parameters = []): string {
/** @var \Symfony\Component\Routing\Route $route */
$route = \Drupal::service('router.route_provider')
->getRouteByName($route_name);
$requirements = $route->getRequirements();
if (array_diff_key($route_parameters, $requirements)) {
throw new InvalidArgumentException('Invalid route parameters.');
}
$template = $route->getPath();
$find = array_map(fn($key) => '{' . $key . '}', array_keys($route_parameters));
$replace = array_values($route_parameters);
return str_replace($find, $replace, $template);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment