我暂时了解了两个模板引擎,一个是ThymeLeaf,一个是FreeMarker。
项目使用easyui等ui框架时使用freemaker,理由:
- freemaker 类似与jsp学习成本低符合以前使用jsp的习惯
- freemaker性能比thymeleaf好
- 使用了easyui等ui框架很少对html 标签和标签属性进行手动处理,都是通过ajax返回json数据,由ui框架的组件直接渲染
项目中使用纯html时使用thymeleaf,理由:
- thymeleaf可以支持前段浏览器渲染
- thymeleaf代码直接嵌入在标签和标签属性中对标签和属性操作比较方便.(根据服务端返response返回的数据,通过thymeleaf来生成html标签)也就是说,thymeleaf适合做服务器端渲染,通过服务器端模版渲染,客户端收到的是在服务器端根据模版渲染完的html信息. 例如前端使用:bootstrap适合用thymeleaf.
其他思路:
freemarker 不足:thymeleaf由于使用了标签属性做为语法,模版页面直接用浏览器渲染,使得前端和后端可以并行开发。freemarket使用</>这样的语法,就无法直接使浏览器渲染出原本页面的样子。
- 从写code的习惯角度可能freemarker更习惯于我们的思维。
- 不过从前后分离开发的角度看thymeleaf更合适,值的绑定都是基于html的dom元素属性的,适合前后联调。
thymeleaf引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
freemarker引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
thymeleaf语法
<b th:text="hello,world!"><b/>
freemarker语法
<h1>${host}</h1>
在html标签里一定要引入 xmlns:th=“http://www.thymeleaf.org” ,这样thymeleaf模板才会启用。