How to get url in Drupal 8?

Member

by brandy , in category: PHP Frameworks , 2 years ago

How to get url in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by dedrick , a year ago

@brandy 

In Drupal 8, you can use the Drupal::request()->getUri() method to get the current URL of the page being accessed.


Here is an example of how you can use this method:

1
$current_url = Drupal::request()->getUri();


You can also use the DrupalCoreUrl class to generate URLs for specific routes in your Drupal site. For example:

1
2
3
4
use DrupalCoreUrl;

$node_url = Url::fromRoute('entity.node.canonical', ['node' => $node->id()]);
$node_url = $node_url->toString();


This will generate the URL for the canonical page of the node with the given ID.


You can also use the DrupalCoreLink class to create a link object, which you can then render as an anchor tag in your twig template. For example:

1
2
3
4
use DrupalCoreLink;

$node_link = Link::createFromRoute($node->label(), 'entity.node.canonical', ['node' => $node->id()]);
$node_link = $node_link->toRenderable();


This will create a link object for the node with the given ID and label, which you can then render in your twig template using the {{ node_link }} variable.


I hope this helps! Let me know if you have any questions.

by haylee.mertz , 9 months ago

@brandy 

In Drupal 8, you can get the current URL using the following methods:

  1. Using the Request object in a controller or custom module: Inject the SymfonyComponentHttpFoundationRequestStack service in your class constructor. Use the $requestStack->getCurrentRequest() method to get the current request object. Finally, use the getUri() method on the request object to get the current URL. Here's an example: use SymfonyComponentHttpFoundationRequestStack; class MyController { protected $requestStack; public function __construct(RequestStack $requestStack) { $this->requestStack = $requestStack; } public function myMethod() { $currentRequest = $this->requestStack->getCurrentRequest(); $currentUrl = $currentRequest->getUri(); // Use $currentUrl as needed. } }
  2. Using the Url class: Use the Url::fromRoute('


Either method will give you the current URL in Drupal 8.