第十节 使用Thymeleaf模版的自定义配置

亮子 2022-02-17 01:57:33 17189 0 0 0

1、自定义模板文件路径

package com.shenmazong.thymeleaf;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Set;

/**
 * @author 军哥
 * @version 1.0
 * @description: 测试自定义配置模板
 * @date 2022/2/18 20:43
 */

@SpringBootTest
public class ThymeleafMakeHtmlTests {

    @Autowired
    TemplateEngine templateEngine;

    @Test
    void testMakeHtml() throws FileNotFoundException, UnsupportedEncodingException {
        //--1 创建上下文
        Context context = new Context();

        //--2 准备页面数据
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", "参码踪");

        //--3 把数据放到上下文中
        context.setVariables(hashMap);

        //--4 定义输出文件名字
        File dest = new File("E:\\opt\\hello.html");
        PrintWriter writer = new PrintWriter(dest, "UTF-8");

        //--5 修改模板文件的位置
        Set<ITemplateResolver> templateResolvers = templateEngine.getTemplateResolvers();
        System.out.println(templateResolvers);
        SpringResourceTemplateResolver iTemplateResolver = (SpringResourceTemplateResolver)templateResolvers.stream().findFirst().get();
        iTemplateResolver.setPrefix("file:E:\\opt\\code\\server-aliyun-demo\\app\\");

        //--6 生成静态文件
        templateEngine.process("hello", context, writer);
    }
}