Search code examples
thymeleaf

What does the Thymeleaf tag "th:for" do?


Anyone know that "th:for" is in Thymeleaf? I know it's a simple question, but I can't find the answer online, even in the Thymeleaf documentation.


Solution

  • It is the Thymeleaf attribute equivalent of the HTML for attribute used by <label> elements. For example:

    <div class="preference">
        <label for="cheese">Do you like cheese?</label>
        <input type="checkbox" name="cheese" id="cheese">
    </div>
    

    It is listed in the Thymeleaf documentation section 5.2:

    There are quite a lot of attributes like these, each of them targeting a specific HTML5 attribute...

    It's no different from most other HTML attributes which have a Thymeleaf version - you can use it with a Thymeleaf expression. If you don't need a Thymeleaf expression, just use the plain for attribute instead.