How to add classes to links in Drupal 8

November 16, 2015

As I start porting the modules I maintain to Drupal 8, I’m hitting a few places where things haven’t been intuitive to me. I’ll try to work on the drupal.org documentation when I get a chance, but in the meantime I figured it would be worth writing up a few notes.

A common task is creating a link, and adding classes and other attributes to it. The Responsive Share Buttons is basically just a block of links to social networks, so this was a key building block.

In Drupal 7 this was pretty simple - the link building function took three arguments - a title, a path, and an array of options:

$link = l(t('Link Title'), 'http://drupal.org', array(
  'attributes' => array(
    'class' => array(
      'my-first-class',
      'my-second-class',
    ),
  ),
));

In Drupal 8, the l function now takes a Url object with attributes, rather than a string, so it’s a little different. Here’s how to build a link to an external URL and add a class to it: First the Url class needs to be brought into scope:

use Drupal\Core\Url;

And then you can build the Url object and call setOptions on it:

$url = Url::fromUri('http://drupal.org');
$link_options = array(
  'attributes' => array(
    'class' => array(
      'my-first-class',
      'my-second-class',
    ),
  ),
);
$url->setOptions($link_options);
$link = \Drupal::l(t('Link title'), $url);

Incidentally, the other gotcha here that had me scratching my head for a while was how to get the current page title, and how to get the current URL. Drupal 7 had easily accessible functions for these tasks, but the object-oriented approach

Drupal 7

$title = drupal_get_title();
$current_url = url(current_path(), array('absolute' => TRUE));

Drupal 8

$request = \Drupal::request();
$route_match = \Drupal::routeMatch();
$title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
$current_url = $request->getUri();

My own learning journey with Drupal 8 is very much in its early days, and a lot of the old Drupalisms are pretty familiar to me, but it does seem a little long-winded. Give it a while, and I’m sure I’ll get up to speed, and start seeing the benefits of the object-oriented approach in Drupal 8.