下面说到的在thymeleaf官网上都可以找到,这里只做个总结
2019-04-21 更新
新增一些用法
取值
@GetMapping("/")
public String index(Model model) {
model.addAttribute("name", "hello thymeleaf");
return "index";
}
使用 th:text 属性展示数据
区别:
#{name} 获取的是国际化的数据
${name} 获取controller里设置在Model里的数据
@{/about} 这种用法在下面有介绍,是动态超链接的写法
[[${name}]] 与${name}效果一样,只不过这种方式是写在标签内容里的,${name} 是写在标签属性里
for循环
在controller里设置在Model里一个List数据,然后在thymeleaf里循环取出来展示在页面上
@GetMapping("/")
public String index(Model model) {
List list = Arrays.asList("Spring", "Java", "NodeJS", "Python");
model.addAttribute("list", list);
return "index";
}
使用 th:each 属性循环数据
值得一说的是, 循环时还有一个变量,可以取一些有用的数据
istat里还可以取出下面这些属性
index 当前循环的下标,从0开始
count 循环到当前状态下的总条数
size list里的总条数
even/odd even是偶数条数,odd是奇数条数,这个属性可以实现隔行换色等需求
first 是否是第一条数据
last 是否是最后一条数据
逻辑判断
有两种方式可以解决if else展示不同数据
th:if th:unless
th:switch th:case
下面来看一下例子
@GetMapping("/")
public String index(Model model) {
model.addAttribute("flag1", true);
model.addAttribute("flag2", null);
return "index";
}
其实 th:unless可以看成是else的意思
循环map
@GetMapping("/")
public String index(Model model) {
Map user = new HashMap();
user.put("name", "tomcat");
user.put("age", 20);
user.put("address", "Shanghai");
model.addAttribute("user", user);
return "index";
}
``html
[[${user.key}]] - [[${user.value}]]
跟循环list一样,循环map也可以获取到当前的循环状态
``html
thymeleaf模板里用spring-security的tags
注意 没有hasPermission()方法,在pom.xml里要引入
org.thymeleaf.extras
thymeleaf-extras-springsecurity4
html页面写script
/*
function notificationCount() {
$.ajax({
url: "/api/notification/notRead",
async: true,
cache: false,
type: "get",
dataType: "json",
success: function (data) {
if (data.code == 200 && data.detail > 0) {
$("#badge").text(data.detail);
}
}
});
}
notificationCount();
setInterval(function () {
notificationCount();
}, 120000);
/*]]>*/
动态生成restful风格的url
query风格的url
页面动态增减class样式
//如果isActive是true,渲染出
//
调用实体类里的方法并传值
//调用属性
//调用方法
//给方法传值
//其实跟velocity, freemarker的用法是一样的,我最开始受th:href="@{/user/(name=${user.name})}"的影响,给弄错了,还以为不支持呢。。
写入行间属性
//
END
原文链接: https://tomoya92.github.io/2017/03/09/spring-boot-thymeleaf-attribute/