美文网首页
thymeleaf简单使用

thymeleaf简单使用

作者: 梦想怪 | 来源:发表于2016-12-06 17:04 被阅读0次

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模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。

1、在项目中添加引用

1、maven的引用方式:

<dependency>    
    <groupId>org.springframework.boot</groupId>    
    <artifactId>spring-boot-starter-thymeleaf</artifactId>    
</dependency>   

2、gradle的引用方式:

compile "org.springframework.boot:spring-boot-starter-thymeleaf"  

2、在controller编写代码,返回视图

@RequestMapping("/index")
public String index(ModelMap map) {    // 加入一个属性,用来在模板中读取    
  map.addAttribute("host", "http://www.bilibili.com");   
  // return模板文件的名称,对应src/main/resources/templates/index.html   
  return "index";
}

3、index.html

<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org">
<head lang="en">   
 <meta charset="UTF-8" />    
<title></title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>

4、运行效果

bilibili.png

5、其他

# 代表 获取对象 从 messages bundle 也就是消息的资源本地化文件
$ 表示从model里面获取
th:fragment=“public” 相当于 include标签
th:each="user : ${users}" 相当于c:foreach
如:

<tr th:each="user : ${users}">
  <td th:text="${user.id}">2333333</td>
  <td th:text="${user.name}">红红火火恍恍惚惚</td>
</tr>

th:text表示动态设置属性的值
th:action用于表单的action
th:if用作if判断
内联js:

<script th:inline="javascript">
/*<![CDATA[*/
...var username = /*[[${sesion.user.name}]]*/ 'Sebastian';...
/*]]>*/
</script>

js附加代码:

/*[+
var msg = 'This is a working application';
+]*/

js移除代码:

/*[- */
var msg = 'This is a non-working template';
/* -]*/

先就这么多吧~~

相关文章

网友评论

      本文标题:thymeleaf简单使用

      本文链接:https://www.haomeiwen.com/subject/xuyrmttx.html