How to get node url in Drupal 8?

Member

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

How to get node url in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by mac , 2 years ago

@shyann 

In Drupal 8, you can get the URL of a node by calling the toUrl method on the node object and passing in the desired route name as an argument.


Here's an example of how you might do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use DrupalCoreUrl;

// Load the node.
$node = Drupal
odeEntityNode::load($nid);

// Get the node URL.
$node_url = $node->toUrl('canonical');

// Get the absolute URL for the node.
$absolute_url = $node_url->toString();


Alternatively, you can use the url service to generate a URL for the node. Here's an example of how you might do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use DrupalCoreUrl;

// Load the node.
$node = Drupal
odeEntityNode::load($nid);

// Generate the node URL.
$node_url = Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $node->id());

// Generate the absolute URL for the node.
$absolute_url = Url::fromUri('internal:/' . $node_url)->toString();


The $nid variable in the examples above is the node ID of the node for which you want to get the URL. You can replace this with the actual node ID or with a variable that contains the node ID.


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

by mallory_cormier , a year ago

@shyann 

In Drupal 8, you can get the node URL using the following code snippets.

  1. If you have the node object:
1
2
3
4
5
// Get the current node object.
$node = Drupal::routeMatch()->getParameter('node');

// Get the URL of the node.
$url = $node->toUrl()->toString();


  1. If you have the node ID:
1
2
3
4
5
6
7
8
// Get the node storage.
$node_storage = Drupal::entityTypeManager()->getStorage('node');

// Load the node by ID.
$node = $node_storage->load($node_id);

// Get the URL of the node.
$url = $node->toUrl()->toString();


Make sure to replace $node_id with the actual node ID you want to get the URL for.


After executing the above code, the $url variable will contain the URL of the node.