← Back to postsDrupal 8/9 – Adding ID Attributes in TWIG

Drupal 8/9 – Adding ID Attributes in TWIG

Published: 9/14/2021

Named anchors are helpful when you need to navigate users to sections within a page. It's a rather common request and should be easy to implement. However, page sections might be built with Paragraphs, Layout Builder components, blocks or something else. So how do you render section IDs so that you can create named anchors linking directly to those sections?

Most scenarios I encounter fall into one of two categories.

#1 - The content or component has a field for manually entering an ID value

Let's say I have a content type with a field named field_custom_identifiers that can be populated with an ID value. This scenario requires a content editor to be aware of, and populate, this field with the desired value. That value can then be rendered in the TWIG template as an ID.

In this example, field_custom_identifiers can be used to add an ID as well as other custom classes. This method extracts only the first value of that field before a space, and turns it into an ID. Also note that the clean_class filter will convert underscores ( _ ) into hyphens ( - ).

{% if node.field_custom_identifiers %}
{% set section_name = node.field_custom_identifiers.value|split(' ')[0]|clean_class %}
{% endif %}

<div id="{{ section_name }}">

{{ ...other content }}

</div>

#2 - The ID value must be created dynamically from some existing field

In this scenario, let's say my content type only contains fields for Title, Description, and Image. But I need to take one of those fields and use it as an ID value. The field that makes the most sense here is Title. But even if the Title field is short, plain text, it likely contains spaces. I could do something like the above example, where I extract the first value before a space:

{% if node.field_title %}
{% set section_name = node.field_title.value|split(' ')[0]|clean_class %}
{% endif %}

<div id="{{ section_name }}">

{{ content.field_title }}
{{ ...other content }}

</div>

But what if most of my titles started with the word "the" or some other common word? Having multiple sections on a page with the same ID is semantically incorrect. Therefore, it might be better to do something like this, which instead converts spaces into hyphens:

{% set title_val = (render_var(content.field_title.0)) %}
{% set section_name = title_val|replace({' ': '-'}) %}

<div id="{{ section_name }}">

{{ content.field_title }}
{{ ...other content }}

</div>