I just had a Drupal 8 site break when moving it from a top-level domain on a server to a subdirectory on my desktop machine: apparently that subdirectory wants to be included in the URL as converted from routes. This threatens to ruin my sandbox environment so I would like to figure out 1) why this is happening and/or 2) what isn't portable about my code fragment below. I've been using
to get the URL Alias of the current page: e.g., the RouteMatch passed as argument to the breadcrumb service. On the server, this returns a proper pathname relative to the top-level domain, for instance:
... but running the same code in my sandbox (http://localhost/mySite) includes the subdirectory name, as if Drupal is returning the URL relative my local web server's document root, instead of the root of my Drupal site:
I realise there may be better ways to get the current URL Alias (e.g.,
\Drupal::service('path.current')->getPath() and then passing it to
\Drupal::service('path.alias_manager')->getAliasByPath, but I'd really like to convert the route itself since that's the argument to the breadcrumb builder in Drupal 8.
p.s., clarification, tentative answer: it is clear from comments below that the variable
$base_path is expected to be used here, and that "base path" is how one refers to the name of the site subdirectory (if there is one). Neither of these were known to me when I submitted my question above and I can safely say they're not detailed in the Drupal 8 documentation either. Therefore the question becomes trivial: "How do I strip out that string from the provided URL?" and the answer is a matter of text processing:
global $base_path; $route_url = Url::fromRouteMatch($route_match)->toString(); $alias_url = substr($route_url, strlen($base_path) - 1);
p.p.s., maybe a better answer: I think I know why comments suggest that finding the URL Alias from the request is the wrong approach, since the
path.current service factors out any base path beautifully, without the gross string processing as above, and works fine in a breadcrumb builder:
$current_path = \Drupal::service('path.current')->getPath(); $alias_from_path = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
Sorry for all the fuss here: from my not knowing about the global variable
$base_path or about how the Drupal services already deal with subdirectory installations. Looking forward to the answer as expressed by other contributors with an eye on the big picture.