Generating Dynamic Identifiers with Thymeleaf

Featured image for sharing metadata for article

If you're working with Thymeleaf templating, you may end up with the case where you're iterating through a set of elements, and want to add a dynamic id attribute to each one, so you can i.e. interact with them using JavaScript.

Although there are quite a few questions on StackOverflow, it turns out that it's not super well documented how to do this.

In Thymeleaf 3, we can use ids.seq for this, as noted in the documentation:

    th:each="property: ${postType.getProperties()}"

This then produces the following HTML:

  <li id="property1">content</li>
  <li id="property2">Date Published</li>
  <li id="property3">Category / tag</li>
  <li id="property4">Whether the post is `published` or `draft`</li>
  <li id="property5">Syndication URL</li>

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #java #thymeleaf.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.