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

Submitted by christophe on Thu, 07/04/2016 - 07:24

The l() function is deprecated in Drupal 8, here is a starter.

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('https://colorfield.be');
$link = Link::fromTextAndUrl(t('Colorfield'), $url);
$link = $link->toRenderable();
$link['#attributes'] = array('class' => array('my-link-class', 'another-class'));
$output = render($link);

Some variations can be obtained, based on the url :

  • Internal route, provided in 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>', array(), array('fragment' => 'my-anchor-name'));

Drupal.org references

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.