Creating links in Drupal 8

in custom code

In this blog post you will learn how to create internal an external links in Drupal 8.

In Drupal 7 websites we created links by using the l() function but in Drupal 8 this changed (surprise surprise :)).

Internal link

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

$options = array(
  'attributes' => ['class' => ['link']],
  'absolute'   => TRUE,
);

$link = Link::fromTextAndUrl(t('Link to my blog'), Url::fromUri('internal:/node/1', $options))->toString();

The following link would be created:

Link to my blog

External link

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

$options = array(
  'attributes' => ['class' => ['link']],
);

$link = Link::fromTextAndUrl(t('Link to google'), Url::fromUri('https://www.google.com', $options))->toString();

The following link would be created:

Link to google

Creating a link by using the route name

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

$link = Link::fromTextAndUrl(t('View reports, updates, and errors'), Url::fromRoute('system.admin_reports', [], ['absolute' => TRUE]))->toString();

The following link would be created:

View reports, updates, and errors
Drupal
Development

Meer leesvoer

I have been working on a Drupal 8 multisite and at some point I had to set up a new site in the structure. The...
Drupal
In this blog post you will learn how to add a theme field preprocess function in your theme.
Theming
In this blog post I show you how to login and logout from a Drupal 8 Back-end from an Ionic app
Drupal
It's quite easy to create a node with REST in Drupal 8, in this blog post I'll show you how to do it.
Drupal