thymeleaf学习笔记

一、Spring Boot中指定静态资源和Thymeleaf模板文件地址时一定要使用路径分隔符结尾(linux:/,windows:\\),否则页面加载时访问不到模板文件,如:spring.resources.static-locations: classpath:/static/

在 javascript 代码中使用 Thymeleaf 模板引擎:

<script th:inline="javascript"> $("#content").html( "<select name='status'>"+ " <option value=''>[[#{admin.common.choose}]]</option>"+ " <option value="+[[${status}]]+">[[#{'Order.Status.' + ${value}}]]</option>"+ "</select>"); </script>

script 标签中的 th:inline="javascript" 属性值表示可以使用内联 js ,即可以在 js 代码中使用 [[]] 取值:

 var user = [[${user}]];

以上是在 Javascript 代码中使用 Thymeleaf 模板引擎的简单示例,但有时也会遇到不可解决或者说很难解决的问题。例如,如果要在 js 代码中输出一个段 html 代码,并且要在 html 代码中作循环操作,而 html 本身并没有提供这种功能的实现,这时要使用 Thymeleaf 的 th:each 属性,但是如何使用 th:each 在 js 中实现? 这时就不能像上面那样的使用字符串拼接内联 js 来实现了,因为 th:xx 是要作为标签的属性放在标签内部的,js 解析不了。解决的方案是将 html 代码放在一个使用 text/html 解析的 script 标签中,这样就会使用 html 的解析方式来解析这些代码,示例如下:

<script type="text/html" id="thymeleafTable"> <table> <tr> <th th:text="#{Order.type}"></th> <td> <select name="type"> <option value="" th:text="#{admin.common.choose}"></option> <option th:each="value : ${types}" th:value="${value}" th:attr="selected = ${value == type} ? 'selected' : ''" th:text="#{'Order.Type.' + ${value}}"></option> </select> </td> </tr> </table> </script> 

然后在 js 代码中使用脚本的 id 来调用该脚本:

$("#content").html($("#thymeleafTable").html());  

text/csstext/html 和 text/javascript 等属性值规定脚本的 MIME 类型,它表示浏览器的解释方式,例如,text/javascript 告诉浏览器按照 Javascript 来解析执行。

转载于:https://www.cnblogs.com/jxrichar/p/7700957.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值