I'm generating the URL inside a controller in a custom module. The URL I generate is to pages on the same site, but not in the module. I want to append an arbitrary number of slugs to the end of the base URL. Some slugs depend on the return values from other API calls, so there's no way to predict how many there are, or what they will be.

I want to generate a $url variable of the form:


I have tried using:


But cannot figure out how to get the base route for the website from it. Or how to add arbitrary slugs.

This was trivial in Drupal 7 and earlier, but I cannot find how to do it in Drupal 8. In Drupal 8, how do you generate arbitrary internal URLs from a module? What should I be doing?

1 Answer 1


From the Drupal API docs for Url::fromRoute()

Creates a new Url object for a URL that has a Drupal route.

This method is for URLs that have Drupal routes (that is, most pages generated by Drupal). For non-routed local URIs relative to the base path (like robots.txt) use Url::fromUri() with the base: scheme.

For this method, you need to provide the route name as defined in your module's .routing.yml file, along with an array of parameters in your route:

\Drupal\Core\Url::fromRoute('mymodule.my_route', array('route_param' => 'param_value'))->toString();

Alternatively, if you don't have a route to plug into you can use Url::fromUri() as the docs specified:

\Drupal\Core\Url::fromUri('base:/any/number/of/arbitrary/slugs',array('absolute' => TRUE))->toString();
  • thanks, I was missing the 'base:'call in fromUri. It then worked. In regards passing in a route to fromRoute, if the route is arbitrary and not part of the module then how do you define it? My reading of the documentation is that you cannot create a route in the routing.yml file without a Controller, so how could you access a route from core, or your theme, or another module from with a module?
    – tanbog
    Commented Jul 21, 2016 at 6:49
  • Look at your site's router table; it contains data on all defined routes. You should be able to find the route name/path you want to access.
    – Shawn Conn
    Commented Jul 21, 2016 at 7:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.