// Get the node object $node = \Drupal\node\Entity\Node::load(1); // Generate the URL $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $node->id()]) ->toString();
// Generate an external URL $url = \Drupal\Core\Url::fromUri('https://www.example.com/') ->setOptions(['attributes' => ['target' => '_blank']]) ->toString();In this example, we generate an external URL to the `example.com` website using the `fromUri()` method. We can then set any options for the URL, such as opening it in a new window, using the `setOptions()` method. Finally, we call `toString()` to get the final URL. Package library: Drupal\Core\Url.