liveBook · Manning

Th:each

As explained in Spring in Action, Sixth Edition

th:each is a Thymeleaf namespace attribute that repeats element rendering for each item in a collection.

th:each is a Thymeleaf namespace attribute that repeats an HTML element for every item in a collection. Each iteration binds the current item to a template variable. section 2.1.3

A typical form uses th:each to build repeated controls from model data:

  • Place th:each on the element to repeat, such as <div th:each="ingredient : ${wrap}">. section 2.1.3
  • Read the current item through the bound variable, such as ingredient.id and ingredient.name. section 2.1.3
  • Combine th:each with th:value, th:field, and th:text to render functional, state-preserving checkbox controls. section 2.1.3
<h3>Designate your wrap:</h3>
<div th:each="ingredient : ${wrap}">
  <input th:field="*{ingredients}" type="checkbox" 
         th:value="${ingredient.id}"/>
  <span th:text="${ingredient.name}">INGREDIENT</span><br/>
</div>

Shows a complete th:each pattern for rendering wrap ingredients as checkbox inputs and labels. section 2.1.3

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains collection iteration, variable binding, property access, and rendered output, but does not detail Thymeleaf internals.
Examples
Uses taco ingredient collections to render wrap checkboxes and ingredient-name labels.
What it assumes
Assumes basic HTML and request or model attributes while showing Thymeleaf syntax through a form example.
What you can do after
Apply it via Thymeleaf to generate repeated form elements from collection data.
How it connects
Connects Thymeleaf templates with HTML, model data, th:text, th:value, and th:field.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.