thymeleaf个人学习

179 阅读1分钟

Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide an elegant and highly-maintainable way of creating templates. To achieve this, it builds on the concept of Natural Templates to inject its logic into template files in a way that doesn’t affect the template from being used as a design prototype. This improves communication of design and bridges the gap between design and development teams.
Thymeleaf has also been designed from the beginning with Web Standards in mind – especially HTML5 – allowing you to create fully validating templates if that is a need for you.

一、第一个例子(非web环境)

package huiqing.thymeleaf;

import org.junit.Test;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


public class MyTest {

    @Test
    public void test01(){
        //创建模板引擎
        TemplateEngine engine = new TemplateEngine();
        //准备模板
        String input = "<input type='text' th:value='${name}'/>";
        //准备数据
        Context context = new Context();
        context.setVariable("name","张迪");//设置上面那个name的值
        //处理模板和数据
        String out = engine.process(input, context);
        System.out.println(out);
    }



}
输出结果:
<input type='text' value='张迪'/>

在html中应用thymeleaf

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text" th:value="${name}"/>

</body>
</html>
@Test
public void test02(){
    //准备模板引擎
    TemplateEngine engine = new TemplateEngine();
    //读取磁盘中的模板文件
    ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
    //设置引擎使用resolver
    engine.setTemplateResolver(resolver);
    //指定数据
    Context context = new Context();
    context.setVariable("name","张慧庆");
    //处理模板
    String out = engine.process("main.html", context);//如果html没有放在resource目录下,则要写出他的绝对路径
    System.out.println(out);
}

输出结果节选
<body>
    <input type="text" value="张慧庆"/>

</body>

设置模板文件的前缀后缀
在resource下新建一个template文件夹,把用到的html文件放进入。

@Test
public void test03(){
    //准备模板引擎
    TemplateEngine engine = new TemplateEngine();
    //读取磁盘文件
    ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
    engine.setTemplateResolver(resolver);
    //设置前缀
    resolver.setPrefix("template/");
    //设置后缀
    resolver.setSuffix(".html");
    //准备数据
    Context context = new Context();
    context.setVariable("name","zhangsan");
    String out = engine.process("index", context);//写html文件的名字
    System.out.println(out);
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<input type="text" value="zhangsan"/>
</body>
</html>