thymeleaf 超链接_thymeleaf模板属性的用法(更新:增加了if, each, 取值用法介绍)

下面说到的在thymeleaf官网上都可以找到,这里只做个总结

2019-04-21 更新

新增一些用法

取值

@GetMapping("/")

public String index(Model model) {

model.addAttribute("name", "hello thymeleaf");

return "index";

}

使用 th:text 属性展示数据

[[${name}]]

区别:

#{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";

}

show this when flag1 is true.
show this when flag1 is false.
show this when flag2 is true.
show this when flag2 is false.
flag2 != true and flag2 != false

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

[[${user.key}]] - [[${user.value}]] - [[${istat.index}]]

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

//hello world

query风格的url

//hello world

页面动态增减class样式

//如果isActive是true,渲染出

//

调用实体类里的方法并传值

//调用属性

//调用方法

//给方法传值

//其实跟velocity, freemarker的用法是一样的,我最开始受th:href="@{/user/(name=${user.name})}"的影响,给弄错了,还以为不支持呢。。

写入行间属性

//

END

原文链接: https://tomoya92.github.io/2017/03/09/spring-boot-thymeleaf-attribute/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值