使用Thymeleaf渲染html模板
阿新 • • 發佈:2018-12-10
使用Thymeleaf來渲染html模板
step1:新增Thymeleaf依賴
<!-- Thymeleaf 模板引擎 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
step2:建立HtmlTemplateUtils.java實現模板渲染
package com.lfsenior.service.sms.util;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.util.Map;
/**
* Created by dlupan on 2018/12/6
*/
public class HtmlTemplateUtils {
private final static TemplateEngine templateEngine = new TemplateEngine();
/**
* 使用Thymeleaf渲染HTML
* @param template HTML模版
* @param params 引數
* @return 渲染後的HTML
*/
public static String render(String template, Map<String, Object> params) {
Context context = new Context();
context.setVariables(params);
return templateEngine.process(template, context);
}
}
step3:編寫渲染測試類
import com.lfsenior.service.sms.util.HtmlTemplateUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Created by dlupan on 2018/12/6
*/
public class TestTemplateEngine {
public static void main(String[] args){
String template="<p th:text='${title}'></p>";
Map<String,Object> params=new HashMap<String,Object>();
params.put("title","Thymeleaf 渲染 HTML ----LFSenior");
String output = HtmlTemplateUtils.render(template, params);
System.out.println(output);
}
}