我踩的thymeleaf渲染框架的坑

来源:互联网 发布:广电网络是国企吗 编辑:程序博客网 时间:2024/06/16 13:29

最近公司用的thymeleaf来做前段渲染框架,老实说我比较喜欢它对html代码的0入侵,但是正因为这一点我又觉得好坑,无法像freemarker那样随便输出动态数据,所有的东西都得和标签有些关联才行。

1. thymeleaf渲染元素属性值的坑

公司有个业务上我需要对a标签的href属性加一个动态id参数上去,

<a href="asda?id={user.id}">click</a>

这里我准备吧{user.id}替换为动态的值,但是,thymeleaf坑来了,它是不允许你这样干的,这样干最后得出的结果就是值渲染不上去,然后我又试了好几种办法,比如加上[[${user.id}]]上去,失败·····

最后,天无绝人之路,有了解决办法
使用th:attr标签来做

th:attr="href=asda?id=${user.id}"

然而,渲染的时候竟然给我报错了。。。。让我感觉应该是字符串拼接的问题。最后加了个单引号,终于解决问题。。。哭晕在地…..

th:attr="href='asda?id='+${user.id}"

最后完整的格式:

<a th:attr="href='asda?id='+${user.id}">click</a>

2017年3月23日更新
其实还可以这样去做,如下

<a th:href="'asda?id='+${user.id}">click</a>

2. thymeleaf3做layout布局的坑

要做layout布局,首先得给TemplateEngine添加一个layout Dialect才行,然而我一开始并不知道,配置方法:

 public TemplateEngine templateEngine() {    SpringTemplateEngine engine = new SpringTemplateEngine();    engine.setTemplateResolver(templateResolver());    engine.setEnableSpringELCompiler(true);    engine.addDialect(new LayoutDialect());    return engine;  }

如果不设置EnableSpringElCompiler为true,项目run的时候会失败并报错。。找了半天。配置好后,其他的问题都已经不是问题,需要注意的是,使用layout布局需要对子页面进行的html标签添加一个layout属性,例如:

<html lang="en" layout:decorator="mobile/layout">

3.Spring Boot 配置thymeleaf3.

由于默认的spring-boot-starter-thymeleaf 使用Thymeleaf2.1,我们要使用thymeleaf3去替换thymeleaf和thymeleaf-layout-dialect版本号,例如

<properties>    <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>    <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version></properties>

详细的配置请查看Spring Boot 官方的thymeleaf3的demo演示。
如果你使用了其他的自动配置Thymeleaf,应该去复写他们的版本号。

0 0
原创粉丝点击