Main menu

Twig: HTML links and variables.

10.18.17

One of the main new features of Drupal 8 is the Twig template engine because its workflow is very different from what we use to do in Drupal 7.

As a first impression when we consult the Twig documentation it looks like everything you need to start working is there -or almost anything-. But it will be during the day to day where you will find to problems that need solving.

In this post the issue is about adding a link in Twig using the link($text, $url, $attributes) function that we can find in Drupal core. As you can guess it needs the text and a url (that can be a url Object) or simply a text string with the address. In Twig we can use objects that can be converted “magically” to strings using __toString().

But what happens when we need the text to include HTML? And what if it is HTML and a variable? The first answer is no, we can’t add that code into the function call. We should define a variable that contains the code we want inside the link. Something like this:

Is interesting to highlight that in this function we can use Drupal paths as value for the address. For example:

{{ link(text, 'internal:/user/login', {'class': ['class__link']}) }}

For that we use the prefix “internal” or “base:” that are part of the Url object schema. The former we will use for path that Drupal knows about and the latter should be used for addresses that don’t need the Drupal routing system such as static files.

In the other side if we want that link to take us to the homepage of the site we will use only “base:”, since it represents the drupal base path and if we need the address for the current page “internal:” can be used.