Skip to main content

Do you want to know how to add a node alias in a twig file?  Rather than do the set up in a custom module or using your theme file.

To be able to create a node alias in a twig file you need to know the node.nid value.  Obviously without it you have nothing to reference from.  In this example, the node.nid value is extracted during a loop.  A fairly standard loop such as

{% for row in rows %}
    // ... script doing some magic ... //
{% endfor %}

Begin by setting the nid value from the row:

{% set nid = row.content['#row']._entity.nid[0].value %}

Using the nid value, now you can load the node alias from the entity node canonical

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

The above two variables are set in the loop as follows:

{% for row in rows %}
    {% set bottomBorder = (not loop.last) ? 'tw-pt-12 tw-pt-4 tw-border-b tw-border-gray-200' : NULL %}
    {% set author = row.content['#row'].related_user %}
    {% set summary = row.content['#row']._entity.body.0.value %}
    {% set nid = row.content['#row']._entity.nid[0].value %}
    {% set alias = path('entity.node.canonical', {'node': nid}) %}

    // ... doing some code magic ... //
{% endfor %}

Which is finally placed in to your href:

<a href="{{ alias }}" title="{{ row.content['#row']._entity.title.value|render }}">
    <h4 {{ title_attributes.addClass('node__title tw-text-grey-dark tw-text-3xl') }}>
         {{ row.content['#row']._entity.title.value|render }}
    </h4>
</a>

 

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...