Thymeleaf模板的使用和WebJars使用

2018-09-08  本文已影响0人  落幕晟伤

Thymeleaf定义

是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。

使用步骤

  1. 引入依赖

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

student类

@Configuration
@Data
public class Student {
private String name;
private int age;
private String male;
private String studentNo;
}

控制层

@Controller
public class IndexController {
@Resource
private Student student;
@GetMapping(value = "/index")
public String index(ModelMap map){
    student.setName("huang");
    student.setAge(20);
    student.setMale("male");
    map.addAttribute("student",student);
    return "index";
 }
}

页面

<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
<title>主页</title>
</head>
<body>
<div class="container"><br/>
<div class="alert alert-success">
    <p   th:text="${student.name}"></p>
    <p   th:text="${student.age}"></p>
</div>
</div>
</body>
</html>

运行结果



语法

改写html标签

<html xmlns:th="http://www.thymeleaf.org">

获取变量

<p   th:text="${student.name}"></p>

循环迭代多条数据

静态

另外$表达式只能写在th标签内部,不然不会生效,上面例子就是使用th:text标签的值替换p标签里面的值,至于p里面的原有的值只是为了给前端开发时做展示用的.这样的话很好的做到了前后端分离.
Thymeleaf的语法有很多,仅更新到以学内容,后续会有更新

WebJars使用

Web前端使用了越来越多的JS或CSS,如jQuery,Backbone.js和Bootstrap。一般情况下,我们是将这些Web资源拷贝到Java Web项目的webapp相应目录下进行管理。这种通过人工方式管理可能会产生版本误差,拷贝版本错误,漏拷等现象,导致前端页面无法正确展示,版本不一致,文件混乱等,导致出现一些莫名其妙的错误等。

加入依赖

<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7-1</version>
</dependency>

页面

<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
上一篇 下一篇

猜你喜欢

热点阅读