Module Development

Generate URLs and Output Links for Drupal 8, 9, 10, and 11

Linking to things is probably one of the first things you learned how to do as a web developer. Anchor tags are the framework of how the world wide web works. So it's important to know how to create them in Drupal. Chances are you'll be doing a lot of it.

Creating links to things in Drupal, however, is a bit more complicated than just typing out an HTML anchor tag. It requires understanding how URLs are generated from routes, and how to define links as renderable arrays. It can also be tricky because of the multitude of deprecated, but still functioning, ways of creating links.

In this tutorial we'll:

  • Use the \Drupal\Core\Url class to generate URL objects from routes and external URIs.
  • Use the \Drupal\Core\Link class to create HTML links within a Drupal module.
  • Examine best practices for working with URLs and links in a Drupal module in order to ensure that your code continues to work into the future.

By the end of this tutorial you should be able to link to anything, either internal to your application or external, using Drupal best practices.