Drupal 10: Generate A Link On The Fly

The l() function was used a lot in Drupal 7. The equivalent in Drupal 8+ is the Link class.

use \Drupal\Core\Link;

$url = Url::fromUri('route:user.logout');
$link = new Link(t('Logout'), $url);

There are a number of static helper methods that can generate the object. For example.

// Create from URL.
$url = Url::fromUri('route:user.logout');
$link = Link::fromTextAndUrl(t('Logout'), $url);

// Create from route.
$link = Link::createFromRoute(t('Logout'), 'user.logout');

This generates a Link object, which can be rendered in a twig template, or used like this:

$string = $link->toString();
$string->getGeneratedLink();
// <a href="/en/user/logout">Log Out</a>

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
8 + 11 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.