Andrew Fletcher published: 31 March 2022 (updated) 13 April 2022 1 minute read
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>