27 April 2023

Get the full/absolute URL of a page in Drupal 10 using the Url class. This snippet covers how to get the URL of the current page, a specific route, or an external website, and how to convert the URL object to a string representation of the absolute URL.

The Url::fromRoute() method is used to get the URL of a specific route, while the Url::fromUri() method is used to get the URL of an external website. The keyword is used to get the URL of the current page.

The toString() method is used to convert the URL object to a string representation of the absolute URL.

Source code viewer
  1. use Drupal\Core\Url;
  2.  
  3. // Get the current page URL.
  4. $current_url = Url::fromRoute('<current>');
  5.  
  6. // Get the URL of a specific route.
  7. $route_url = Url::fromRoute('route_name');
  8.  
  9. // Get the URL of an external website.
  10. $external_url = Url::fromUri('https://www.example.com');
  11.  
  12. // Get the absolute URL.
  13. $current_url_absolute = $current_url->toString();
  14. $route_url_absolute = $route_url->toString();
  15. $external_url_absolute = $external_url->toString();
Programming Language: PHP