Thymeleaf #arrays.contains使用
一. 前期准备
⏹下拉列表相关的枚举类
public enum BusinessCodeEnum {
PRICE_ERROR(20, "价格异常"),
CATEGORY_ERROR(30, "种类异常"),
APP_ERROR(1, "订单异常");
private int code;
private String msg;
BusinessCodeEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
⏹页面form
import lombok.Data;
@Data
public class Test24Form {
private String[] categoryList;
private BusinessCodeEnum[] businessCodeEnums;
}
二. Controller层
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/test24")
public class Test24Controller {
@GetMapping("/init")
public ModelAndView init() {
Test24Form form = new Test24Form();
String[] categoryList = {
"1", "2", "3", "4"};
form.setCategoryList(categoryList);
form.setBusinessCodeEnums(BusinessCodeEnum.values());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("test24");
modelAndView.addObject("entity", form);
return modelAndView;
}
}
三. 前台HTML
-
#arrays.contains(数组, 元素):判定元素是否在数组中
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:object="${entity}">
<select>
<!--
⏹th:with="categoryList=*{categoryList}" 创建临时变量
-->
<th:block th:each="enum: *{businessCodeEnums}" th:with="categoryList=*{categoryList}">
<!--
categoryList中的元素都是字符串,
而enum.code是一个数字,
因此必须把code这个数字转换为字符串才可以,
⏹可以通过.toString()转换为字符串
如果枚举类中的code包含在categoryList中,那么就选中
-->
<option th:value="${enum.code}"
th:selected="${#arrays.contains(categoryList, enum.code.toString())}">
[[${enum.msg}]]
</option>
</th:block>
</select>
</div>
</body>
</html>
