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>
Related articles
Andrew Fletcher
•
22 Apr 2024
Streamlined Drupal 10 Deployment: Best Practices for Stability and Security
Have you ever walked into a situation and marveled at how a site is still operational? Deployments that are riddled with fail-safes piled atop a shaky foundation. The real challenge lies in gradually persuading the team to embrace change to build a stable, robust deployment process aligned with...
Andrew Fletcher
•
21 Apr 2024
This command will help you spot any unusually large directories
The red flag was when I saw the server disk space is showing a site is taking up 57992.5 MB, where locally the site size is showing 957MB. There is something serious happening here and I need to establish the problem quickly. When dealing with a significant discrepancy in site size...
Andrew Fletcher
•
19 Apr 2024
Extending a Contrib Module's Configuration in Drupal 10: A Case Study with Sitewide Alert
Extending the functionality of a contrib module in Drupal can enhance its usefulness without altering the original codebase. This article provides a step-by-step guide on how to add custom configuration options to an existing contrib module, using the sitewide_alert module as an example. We will...