Skip to main content

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 to achieve

This is achieved through using the following

{% set alias = path('entity.{type}.canonical', {'{ref}': tid}) %}

Where type can be: node or taxonomy_term to label a couple.  And ref is node or taxonomy_term respectively.  So how does this look against the two entities?

Node alias path:

{% set alias = path('entity.node.canonical', {'node': tid}) %}

Taxonomy term path:

{% set alias = path('entity.taxonomy_term.canonical', {'taxonomy_term': tid}) %}

 

Seeing this in action.  In the scenario below, presenting a node, that has a taxonomy reference field category

{% for category in node.field_category %}
  {% set tid = category.entity.tid.value %}
  {% set term = category.entity.name.value %}
  {% set alias = path('entity.taxonomy_term.canonical', {'taxonomy_term': tid}) %}
  <a href="{{ alias }}" hreflang="en">{{ term }}</a>
  {{ loop.last ? "" : ", " }}
{% endfor %}

 

Related articles

Andrew Fletcher04 Apr 2025
Managing .gitignore changes
When working with Git, the .gitignore file plays a critical role in controlling which files and folders are tracked by version control. Yet, many developers are unsure when changes to .gitignore take effect and how to manage files that are already being tracked. This uncertainty can lead to...
Andrew Fletcher26 Mar 2025
How to fix the ‘Undefined function t’ error in Drupal 10 or 11 code
Upgrading to Drupal 10.4+ you might have noticed a warning in their code editor stating “Undefined function ‘t’”. While Drupal’s `t()` function remains valid in procedural code, some language analysis tools — such as Intelephense — do not automatically recognise Drupal’s global functions. This...
Andrew Fletcher17 Mar 2025
Upgrading to PHP 8.4 challenges with Drupal contrib modules
The upgrade from PHP 8.3.14 to PHP 8.4.4 presents challenges for Drupal 10.4 websites, particularly when dealing with contributed modules. While Drupal core operates seamlessly, various contrib modules have not yet been updated to accommodate changes introduced in PHP 8.4.x. This has resulted in...