The link

Now that we have a Url object, we can use it to generate a link. We can do this in two ways:

  • Use the LinkGenerator service (named link_generator) and call its generate() method passing the link text and the Url object we have obtained. This will return a GeneratedLink object, which contains the actual string representation of the link, that is, the markup.
  • Use the Link class, which wraps a render element (we will talk more about render elements in the Theming chapter) to represent the link.

Let's take a look at an example of both, from start to finish.

Consider this example of generating a link using the service:

$url = Url::fromRoute('my_route', ['param_name' => $param_value]);$link = \Drupal::service('link_generator')->generate('My ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.