java渲染html_模板引擎 Thymeleaf 动态渲染 HTML

file

1、添加依赖

org.thymeleaf

thymeleaf

3.0.9.RELEASE

2、编码工具类 HTMLTemplateUtils.java

import org.thymeleaf.TemplateEngine;

import org.thymeleaf.context.Context;

import java.util.Map;

/**

* HTML模板渲染工具类

*/

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 params){

Context context = new Context();

context.setVariables(params);

return templateEngine.process(template, context);

}

}

3、测试模板引擎

import com.odianyun.util.sensi.HTMLTemplateUtils;

import org.junit.Test;

import java.util.HashMap;

import java.util.Map;

public class TemplateResolverAttributesTest {

@Test

public void testTemplateResolutionAttributes01() throws Exception {

String template = "

Map params = new HashMap<>();

params.put("title", "Thymeleaf 渲染 HTML ---- Anoy");

String output = HTMLTemplateUtils.render(template, params);

System.out.println(output);

}

}

控制台输出

Thymeleaf 渲染 HTML ---- Anoy

相关文档

本文由博客一文多发平台 OpenWrite 发布!

file 1、添加依赖 org.thymeleaf thymeleaf 3.0.9.RELEASE 2、编码工具类 HTMLTemplateUtils.java import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import java.util.Map; /** * HTML模板渲染工具类 */ 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 params){ Context context = new Context(); context.setVariables(params); return templateEngine.process(template, context); } } 3、测试模板引擎 import com.odianyun.util.sensi.HTMLTemplateUtils; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class TemplateResolverAttributesTest { @Test public void testTemplateResolutionAttributes01() throws Exception { String template = " Map params = new HashMap<>(); params.put("title", "Thymeleaf 渲染 HTML ---- Anoy"); String output = HTMLTemplateUtils.render(template, params); System.out.println(output); } } 控制台输出 Thymeleaf 渲染 HTML ---- Anoy 相关文档 本文由博客一文多发平台 OpenWrite 发布!
经验分享 程序员 微信小程序 职场和发展