表达式-Thymeleaf常见用法(一)

来源:互联网 发布:windows账户注册 编辑:程序博客网 时间:2024/06/06 20:48

简介

Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。

Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP,或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。

创建,配置模板引擎

**So what if we wanted to make this template HTML5-valid? Easy: switch to Thymeleaf’s data attribute syntax, using the\

data- prefix for attribute names and hyphen ( - ) separators instead of semi-colons ( : ):**

data- notation is only allowed in HTMLmode.

默认模板文件位置:/WEB-INF/templates/home.html

表达式

其中的标签:th:也可以使用data加上-来代替,也就是 th:href=可以使用data-href=来代替

Spring表达式语言:Spring EL(spel)是变量表达式语言,替代OGNL表达式。

所有的${…},*{…}都会被spel引擎解析,从Spring4.2.4+开始也支持spel compiler。

引用所有的bean对象使用语法: ${@myBean.doSomething()}

在Thymeleaf中新添加处理form表单的有:th:field , th:errors and th:errorclass 它们都是th:object的实现,常用在form表单上面。

对象方法表达式:#themes.code(…)和Spring中jsp标签spring:theme一致。而#mvc.uri(…)和spring:mvcUrl(…)一致(仅Spring 4.1+)

表示url的 @{baidu.com}

th:text或者外部文本:外部文本通常使用独立的配置文件(比如.properties文件)来保存信息,比如用来国际化等。外部的片段文本在Thymeleaf里面成为message。比如配置文件home.properties内容如下:

home.welcome=Welcome to our grocery store, {0} (from default messages)!logo=Good Thymes Virtual Grocery logodate.format=MMMM dd'','‘yyyy

和它同名的模板文件,home.html可以读取其中的内容:

p th:utext=“ #{home.welcome}” Welcome to our grocery store, Sebastian!/p

从WebContext(ServletContext)里面取数据:

${x} will return a variable x stored into the Thymeleaf context or as a request attribute${param.x} will return a request parameter called x (which might be multivalued)${session.x} will return a session attribute called x .${application.x} will return a servlet context attribute called x .

th:text对于html标签会进行转义,这是Thymeleaf默认行为

th:utext (for “ unescaped text” ) 会识别html tags,不进行tags的转义,比如btom/b

0 0
原创粉丝点击