Creating links in Drupal 8 programmatically

Links header

Creating links in Drupal 8 programmatically

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

In Drupal 7 websites we used to create links by using the l() function but in Drupal 8 this changed.

Internal link

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

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

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

This code creates an internal link to node/1

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();

This code creates a link to google.com.

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();

This code creates a link to the admin reports page.

Happy coding!