Explain Codes LogoExplain Codes Logo

Using data-* attribute with Thymeleaf

html
thymeleaf
data-attributes
html5
Alex KataevbyAlex Kataev·Jan 23, 2025
TLDR

Setting data-* attributes with Thymeleaf is done using th:attr, binding their values dynamically like so:

<span th:attr="data-custom=${dataValue}">Text</span>

Look for your target dataValue variable to bring in your required changes instantly.

One tag, multiple data-* attributes

Thymeleaf allows the setting of multiple data- attributes* simultaneously. Simply separate each attribute with a comma (,) within th:attr:

<div th:attr="data-id=${element.id},data-name=${element.name}"></div>

Just like ordering a pizza with extra toppings, you get to add multiple attributes with a single declaration! 🍕

HTML5 and Thymeleaf 3.0: Simplified attribute formatting

Starting Thymeleaf 3.0, attribute processing became much slicker with the Default Attribute Processor. It removed the need for extra dialects when toying with HTML5-friendly data-* attribute names.

<div data-id="${element.id}" data-name="${element.name}"></div>

This modern syntax is cleaner and more streamlined, aligning with the neat vibe of HTML5. It's similar to moving from handwritten letters to instant messaging. 💬

Injecting JSON directly with literal substitution

Thymeleaf's feature of literal substitution successfully injects JSON values into data-* attributes, making the resulting data bindings a valid JSON:

<button th:attr="data-config=${'{' + '\'url\':\'' + element.url + '\'' + '}'}">Click me</button>

The feeling is as amazing as slipping into a fitted suit from a tailored boutique! 🕴️

##tags** on your Instagram posts:

📸 Thymeleaf Snapshot: <div th:text="${tool.name}" data-tool-id="${tool.id}"></div>

The data-tool-id is like your favorite hashtag that helps others find your posts later.

Before: 🧐 ...what was the name of that cool coffee place? After: ☕🔍✅ ...Got it! It was #BestCoffeeEver.

Attributes in HTML are like hashtags for your posts; data-* are your bespoke hashtags that help your content be more discoverable! 🌐

Ensuring XML syntax compliance

While Thymeleaf outputs HTML, it upholds XML rules. Several XML regulations must be kept in mind:

  • Preclusion of duplicate attributes in a single tag.
  • Immaculate use of the correct Thymeleaf syntax

Think of this as an international trip where you must obey the rules of the country you're visiting. 🛄 No one wants a syntax infringement causing a hold-up at customs!

Go beyond with Thymeleaf diaclects

In special use-cases where the core Thymeleaf functionality can feel restrictive, a third-party dialect opens up exciting potentials:

Find it on GitHub: thymeleaf-extras-data-attribute

It's like finding a secret passage in a vintage library, enhancing the classic features for a richer Thymeleaf experience. 📚