Drupal 8 l() function - creating a link

The Drupal link function or l() function is a handy function you've likely used many times over the years of development. All the way back to Drupal 4.6 (my first version of Drupal) it's been a standard, something I've used so many times I don't even have to think about it. Its ability to correctly handle aliased paths, add an active class and an optional destination, makes it simple to implement yet very useful in just about any Drupal site.

With the sweeping changes to Drupal 8 and its routing elements, the l function no longer exists. Well, it still exists as a convience wrapper, but it's being depreciated for Drupal 9 and been replaced with the Link class. Hopefully the few different snippets below will help you as you make the transition from the older l function to the new Drupal 8 way.

Url::fromUri()

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

$options = [
  'query' => ['foo' => 'bar'],
  'fragment' => 'anchor-div',
  'attributes' => ['class' => ['my-class'], 'rel' => 'nofollow'],
];

$result = Link::fromTextAndUrl(t('Drupal 8'), Url::fromUri('internal:/node/1', $options))->toString();

The result will look like this:

Drupal 8

Url::fromRoute()

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

$query =['foo' => 'bar'];
$options = array(
  'fragment' => 'anchor-div',
  'attributes' => ['class' => ['my-class'], 'rel' => 'nofollow'],
);

$result = Link::fromTextAndUrl(t('Drupal 8'), Url::fromRoute('system.admin_config_services', $query, $options))->toString();

The result will look like this:

Drupal 8
Shane Graham

Shane Graham

Shane Graham is a senior Drupal developer and co-founder of Deck Fifty Design.

Get in touch

Let's go!

We look forward to hearing from you!