Drupal - How do I theme a link?

I think the problem with your Drupal 8 code is that '#url' needs a URL object.

External URL

'#url' => Url::fromUri('https://www.drupal.org'),

Internal URL from a route

'#url' => Url::fromRoute('entity.node.canonical', ['node' => 1]),

In Drupal 8 you are not supposed to render yourself. When porting code from Drupal 7, remove all rendering and return only render arrays.


As an alternative, you can also use \Drupal\Core\Link::fromTextAndUrl() or \Drupal\Core\Link::createFromRoute().

Twig can print that as-is, you can also get a render array by calling \Drupal\Core\Link::toRenderable(). The resulting render array is the same then as building it from hand.

Tags:

Theming

8