Get the current page URI on Drupal 8 | Drupal 8

Get the current page URI on Drupal 8

Submitted by editor on Thu, 11/19/2015 - 10:12
Question

How to get the current page uri /url / path / link on Drupal 8 (programmatically) ?

Here an example to get the current page path programmatically in Drupal 8

    $current_url = Url::fromRoute('<current>');
    $path = $current_url->toString();

Exemples for the page /en/user/login:
$current_url->toString(); // /en/user/login
$current_url->getInternalPath(); // user/login
$path = $current_url->getRouteName(); // <current>

Drupal provide several way to do the same things, You can also use following syntax.
$path = \Drupal::request()->attributes->get('_system_path');
$current_uri = \Drupal::request()->getRequestUri();
$current_path = \Drupal::service('path.current')->getPath();
$result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

Get the url of the request

This return the url displayed on the browser.
$page = \Drupal::request()->getRequestUri();

Tags

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.