David Lohmeyer's Blog

Creating links with custom classes in Drupal 8 modules

If you're getting a little frustrated with the new Drupal::l function in D8, which is actually going to be changed to Link in Drupal 9, here's how to create a link with class attributes right now. Attributes like link classes used to be defined on the l() function in Drupal 7, but are now passed into the Url() function as extra options.

Here's the ugly truth in how you link to something within module procedural code. You'll want to put the "use Drupal\Core\Url" at the top of your file:

use Drupal\Core\Url;

     t('My Button'), 
      new Url('my.link.route', 
        ['route_parameter' => $custom_variable],
        ['attributes' => ['class' => ['button']]])

This would output a regular <a> with the "button" class.

Related Posts