Drupal - How do I get the current path alias or path?

Some of the other answers were only correct during previous alpha/beta versions of Drupal 8, or seemed to be incomplete. As of beta7 (and hopefully permanently), the following rules should apply:

For the current raw path (the un-aliased Drupal path):

$current_path = \Drupal::service('path.current')->getPath();

For the current URI, which is pretty-much a direct representation of the request (it may even include a query string):

$current_uri = \Drupal::request()->getRequestUri();

There is of course no guarantee that this $current_uri value will give you an alias, even if one is available for the request, as it only represents what the user has requested. So to strictly do what you are asking about (get alias if available, and path if not) I think you could do:

$current_path = \Drupal::service('path.current')->getPath();
$result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

Of course depending on the type of processing you are doing it may be best to be working with routes instead of paths, but I suppose that's a whole other topic.


The proper way for the URL without the URL alias.

$current_path = \Drupal::service('path.current')->getPath()

In Drupal 8 you can do this with Twig:

{{ url('<current>') }}

example:

<a href="{{ url('<current>') }}">{{ 'Reload'|t }}</a>

from: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

Tags:

8

Path Aliases