Skip to main content

How do I generate URL by term_id (tid) or node_id (nid)

When you have an entity ID value such as node ID (nid) or taxonomy term ID, how can you create the alias in a twig file?  In other words, instead of /taxonomy/term/{tid} I would like to get the alias I have defined for this, eg: /some/path/to/my/term.

In trying to find an answer you might have queried your search criteria using something like

twig canonical taxonomy path

twig canonical entity path

twig canonical node path

 

How do I get a page’s current URL in Twig for Drupal 9

Having access to a site’s URL in your templates can come in handy for many different use cases, such as determining if your on the admin/people page as apposed to admin/reports/dblog or admin/content.  These three pages might seem to bear on common relationship, however there is at least one.  Users.

I edited the user in the admin/people page so rather than showing just username, know shows:

twig add to array [merge, append, push]

Working in Twig, I had to add classes to a pre-existing array.  Whilst I've grown used to the patterns in PHP, these cannot be applied in Twig.  Instead I had to merge the new array elements.

Non associative arrays

Working from a base level, I'll begin as if the original array hasn't been set.  The merge filter expects as first argument an array whose content will be merged with the assigned variable:

Drupal twig look up to access field data

This guide has been compiled as a reference tool on how to access field values for different field types.

The Manage Display admin UI can change how a field’s label and content are displayed. When I want to show how to output just the Manage Display version of the content, I use the word ‘display’. When I’m talking about the more raw version of the content, I use ‘value’.

Subscribe to twig