Colorfield logo


Published on

Drupal 8 links or where is my l() function?


The l() function is deprecated in Drupal 8+, here is how to implement it.

Import the URL and Link classes :

use Drupal\Core\Url;
use Drupal\Core\Link;`

You have several options, but basically, you can start with an url that will be used by a link.
One of the possible implementation will be used, with the Link::fromTextAndUrl method.

Let's start with an external link :

$url = Url::fromUri('');
$link = Link::fromTextAndUrl(t('Colorfield'), $url);
$link = $link->toRenderable();
$link['#attributes'] = ['class' => ['my-link-class', 'another-class']];
$output = \Drupal::service('renderer')->render($link);

Some variations can be obtained, based on the url

Internal route, provided by e.g. a *.routing.yml file

// get the contact form
$url = Url::fromRoute('contact.site_page');
// or a specific node, with absolute URL
$options = ['absolute' => TRUE];
$url = Url::fromRoute('entity.node.canonical', ['node' => 1], $options);

Internal path

$url = Url::fromUri('internal:'.'/my/path); // do not forget the / prefix

Anchor, in the current page

$url = Url::fromRoute('<current>', [], ['fragment' => 'my-anchor-name']]; references