在Thymeleaf的下拉列表中使用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;
}

现在我要使用Thymeleaf标签填充此哈希图。该怎么做?使用核心Spring-mvc标签,我可以做到这一点

<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>

百里香等效于什么?


问题答案:

以下代码与您在问题中发布的带有spring标记的jsp相对应。

<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>