May 20, 2019 in Drupal 8, Snippets

Snippet to create a link with a class programmatically.

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

$link_options = array(
  'attributes' => array(
    'class' => array(
      'button',
      'bg-green'
    ),
  ),
);
$url = Url::fromUri('internal:/node/'.$nid);
$url->setOptions($link_options);
$link = Link::fromTextAndUrl('Click here', $url)->toString();