Creating a link from node ID in Drupal 8
Create absolute URL:
$options = ['absolute' => TRUE];
$url_object = Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
// will output http://example.com/path-to-my-node
Create absolute link object:
$options = ['absolute' => TRUE, 'attributes' => ['class' => 'this-class']];
$node_title = Drupal\Core\Render\Markup::create('<span>' . $node_title . '</span>');
$link_object = Drupal\Core\Link::createFromRoute($node_title, 'entity.node.canonical', ['node' => $nid], $options);
// will output <a href="http://example.com/path-to-my-node" class="this-class"><span>My Node's Title</span></a>
You need to use the \Drupal\Core\Url
class, specifically its fromRoute
static method. Drupal 8 uses routes which have name different from their actual URL path. In your case, the route to use is the canonical route for a node entity: entity.node.canonical
. \Drupal\Core\Url::fromRoute()
will not return a string, but an object. To get the URL as a string, you need to call its toString()
method.
$options = ['absolute' => TRUE];
$url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 1], $options);
$url = $url->toString();
The static method is not easily testable, $url->toString()
require an initialized container. Your can replace the static method with a call to UrlGeneratorInterface::generateFromRoute()
on the url_generator
service.
$options = ['absolute' => TRUE];
$url = $this->url_generator->generateFromRoute('entity.node.canonical', ['node' => 1], $options);
$url = $url->toString();
Unfortunately, this method is marked as @internal
so you are not supposed to use it in user code (ie. outside Drupal core).