Using HashMap in dropdown list in Thymeleaf

℡╲_俬逩灬. 提交于 2020-01-13 05:57:25

问题


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>


来源:https://stackoverflow.com/questions/23991711/using-hashmap-in-dropdown-list-in-thymeleaf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!