Using HashMap in dropdown list in Thymeleaf

2020-07-23 18:09发布

问题:

In my controller I am setting a hashmap

@ModelAttribute("clientImpMap")
public Map<String,String> populateClientImpMap() throws MalformedURLException, IOException 
{

    Map<String,String> clientImpMap = new HashMap<String,String> ();
    clientImpMap.put("1","High");
    clientImpMap.put("2","Low");
    return clientImpMap;
}

Now I want to populate this hashmap using Thymeleaf tags .How to do it? Using core Spring-mvc tags I can do this

<td>Client Importance :</td>
    <td><form:select path="personBean.clientImpRef">
            <form:option value="NONE" label="--- Select ---" />
            <form:options items="${clientImpMap}"  />
        </form:select></td>
    <td><form:errors path="personBean.clientImpRef" cssClass="error" /></td>
</tr>

What is the equivalent of this in thymeleaf?

回答1:

The following code corresponds to the jsp with spring tags that you have posted in your question.

<form action="your-controller-mapping" th:object="${personBean}">
   <select th:field="*{clientImpRef}">
      <option value="NONE">----Select----</option>
      <option th:each="entry : ${clientImpMap.entrySet()}" th:value="${entry.key}" th:text="${entry.value}">
        This will be replaced - is only used for natural templating
      </option>
   </select>
</form>


回答2:

Here is the sample code & link

th:each="item : ${items}" th:text="${item.description}"

Thymeleaf for each for select option & similar scenarios

<ul>
  <li th:each="item : ${items}" th:text="${item.description}">Item description here...</li>
</ul>