<!-- Thymeleaf 模板引擎 --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>3.0.9.RELEASE</version> </dependency>
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<String, Object> params){ Context context = new Context(); context.setVariables(params); return templateEngine.process(template, context); } }
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 = "<p th:text='${title}'></p>"; Map<String, Object> params = new HashMap<>(); params.put("title", "Thymeleaf 渲染 HTML ---- Anoy"); String output = HTMLTemplateUtils.render(template, params); System.out.println(output); } }
控制檯輸出
<p>Thymeleaf 渲染 HTML ---- Anoy</p>
html
Thymeleaf 模板語法java