thymeleaf在script中渲染数组(Array|List)

thymeleaf在script中渲染数组(Array|List)

Xy718 2,532 2019-12-04

    最近在做一些前端的开发,是简单的开箱即用的layui。当然,她不是今天的主角,今天的主角是thymeleaf,记录一点在前后端开发中模板引擎的相关:

thymeleaf如何在< script >标签中渲染java数组

环境介绍:

  • 后端框架:springboot
  • 模板引擎: thymeleaf
  • 前端框架:无

如何在script中使用数组

1、首先在<script>标签内加上th:inline="javascript":

在标签内加上了th:inline="javascript"后thymeleaf即可对js内的代码进行渲染,是要在数据两边加上[[]]即可:

2、后端代码

@GetMapping("/index")
	public String index(
			Model model
			) {
		TestModel[] array= userService.getUserArray();
		List<TestModel> arrayList=userService.getUserArrayList();
		model.addAttribute("array",array);
		model.addAttribute("arrayList",arrayList);
		return "index";
	}

代码中的userServiced的两个函数一个返回普通的java数组,一个返回List数组。

效果

运行项目后访问:http://localhost:8080/indexF12打开网页控制台查看source,点击index文件:

可以看到[[${array}]][[${arrayList}]]都已经被thymeleaf渲染成了数组,不论普通数组还是List,在渲染后的结构都是一样的

ps:本篇博客的git地址:https://gitee.com/Xy_718/ThymeleafArrayinJavaScript.git


冶心·练体·得技