How to get a named route

With slim 4, what’s the way to get the path for a named route when inside a controller method that has access to the request and response?

Also, with twig-view (beta or dev or whichever kinda supports slim 4) is it possible to use path_for( ) in template files?

We’re running into road blocks with both of these…

Hi @dunkoh

Here are some examples:

// Get the url for for the given named route
$routeParser = \Slim\Routing\RouteContext::fromRequest($request)->getRouteParser();
$url = $routeParser->urlFor('route-name', $data, $queryParams);

// Get the full url for the given named route
$routeParser = \Slim\Routing\RouteContext::fromRequest($request)->getRouteParser();
$fullUrl = $routeParser->fullUrlFor($request->getUri(), 'route-name', $data, $queryParams);

// Get the relative url for the given named route
$routeParser = \Slim\Routing\RouteContext::fromRequest($request)->getRouteParser();
$relativeUrl = $routeParser->relativeUrlFor('route-name', $data, $queryParams);

is it possible to use path_for( ) in template files?

Yes, in the latest dev-version of twig-view 3.x. To install it run:

composer require slim/twig-view: "3.x-dev"

Then you have access to: url_for, full_url_for, is_current_url, current_url, get_uri and base_path.

1 Like