Spring boot + thymeleaf 生成静态html文件,实现小程序嵌套模板

1.引入依赖

Maven方式

 <dependency>
        <groupId>org.thymeleaf</groupId>
         <artifactId>thymeleaf</artifactId>
         <version>3.0.7.RELEASE</version>
     </dependency>

Grade方式

compile("org.thymeleaf:thymeleaf:3.0.7.RELEASE")
2.引入两个工具类

ApplicationContextHolder

package com.taoweilai.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;
	@Override
	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
		applicationContext = ctx;
	}
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	
	public static <T> T getBean(Class<T> clazz){
		return applicationContext.getBean(clazz);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name){
		return (T) applicationContext.getBean(name);
	}
}

TemplateUtils

package com.taoweilai.common.utils;

import java.io.FileWriter;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

public class TemplateUtils {
	
	@Autowired
	public static final TemplateEngine engine = ApplicationContextHolder.getBean(TemplateEngine.class);
	/**
	 * 生成静态文件
	 * @param freeTempName 模板名称
	 * @param context 数据内容
	 * @param outFilePath 输出路径
	 * @return
	 */
	public static boolean process(String freeTempName,Context context,String outFilePath) {
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(outFilePath);
			engine.process(freeTempName, context,fileWriter);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				fileWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}
}
3.创建模板

templates/example.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<span th:text="hello + ${name}"></span>
</body>
</html>
4.在单元测试里面测试

在D中创建test目录

@Test
public void testTemplate() {
	String url = "D:/test/";
	Context context = new Context();
	context.setVariable("name", "world");
	TemplateUtils.process("template.html", context, url+"test.html");
}

右击Juint Test运行后
在这里插入图片描述
在文件夹中查看已有文件生成
在这里插入图片描述
开发页面
在这里插入图片描述
生成成功

小程序中使用web-view标签可以嵌套html

 <web-view src="D:/test/test.html"></web-view>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值