With the following snippet you can create a link or button with classes from a route. Use the setOptions() method to add the classes:

$link_options = array(
        'attributes' => array(
          'class' => array(
            'btn',
            'btn-primary',
          ),
        ),
      );
$link = Link::fromTextAndUrl(t('Read more'),
Url::fromRoute('my_route', ['id' => $entity->id()])->setOptions($link_options));
$output = $link->toString();

 


Saved you some valuable time?

Donate and get more free time-saving code on this website in the future.