thymeleaf利⽤th:each循环Map中的List(Map嵌套循环)
后端传送⼀个带List的Map参数返回前台,当使⽤thymeleaf的th:each tag进⾏嵌套输出时发现内循环⽆法正确获取到数据。后台传输对象:
@RequestMapping
public ModelAndView show(HttpServletRequest req, HttpServletResponse resp, Model model){
Map<String,Object> file =new HashMap<>();
List<FileInfo> AA = Arrays
.asList(new FileInfo("A1CLASS","A1ID","A1PATH","A1NAME"),
new FileInfo("A2CLASS","A2ID","A2PATH","A2NAME"),
new FileInfo("A3CLASS","A3ID","A3PATH","A3NAME"));
List<FileInfo> BB = Arrays
.asList(new FileInfo("B1CLASS","B1ID","B1PATH","B1NAME"),
new FileInfo("B2CLASS","B2ID","B2PATH","B2NAME"),
new FileInfo("B3CLASS","B3ID","B3PATH","B3NAME"));
file.put("AA",AA);
file.put("BB",BB);
ModelAndView modelAndView =new ModelAndView("ia11/ia1101/ia1101");
model.addAttribute("file",file);
model.addAttribute("test","test");
return modelAndView;
thymeleaf用法
}
然后在前端使⽤<div th:text></div>标签查看输出内容。
具体HTML代码:
<div id="outDiv"each="map:${file}">
<div class="form-group">
<label id="lable"class="col-md-2">EACH</label>
<div id="document"class="col-md-10">
<div text="${map}"></div>
//in this time the th:each tag is useful
<div each="oneFile:${map}">
<div text="${oneFile}"></div>
// but in this time the th:each tag can't loop the FileInfo object in the AA
<input type="hidden"name="filesData_CLASS"value="${oneFile.fileClass}">
<input type="hidden"name="filesData_FILE_ID"value="${oneFile.fileId}">
<input type="hidden"name="filesData_PATH"value="${oneFile.filePath}">
<div class="input-group">
<input type="text"class="form-control"readonly name="fileChoose_text"value="${oneFile.fileName}">
<span class="input-group-btn">
<button type="button"name="fileChoose_btn"class="btn btn-default btn-flat" >选择</button>
</span>
</div>
</div>
</div>
</div>
</div>
在第⼀个each的时候是可以正常运作的,但是第⼆个each就能循环了。
在⽹上⽤各种姿势搜索都没到结果,于是我去官⽅的github上提问了。
官⽅的回答如下:
When using th:each over Maps, then the value being iterated over is a java.util.Map.Entry type, so when doing your second th:each you need to extract the lists out of the map entry’s value property. So I think something like this will work:
还给出了例⼦:
<div th:each="mapEntry: ${file}">
<div th:each="fileInfo: ${mapEntry.value}">
<input type="text" class="form-control" readonly name="fileChoose_text" th:value="${fileInfo.fileName}">
...
</div>
</div>
⼤致意思是 在使⽤th:each循环map时,他迭代的是Map.Entry所以在第⼆个循环的时候其实是map的⼀对键值对,不是只有值得⼀个List,所以我们需要获取键值对的值,对于值去进⾏循环。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。