使用 Thymeleaf 動態渲染 HTML

一、添加依賴

<!-- 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);
    }

}複製代碼

控制檯輸出 java

Thymeleaf 渲染 HTML ---- Anoy面試

相關文檔

Thymeleaf 模板語法spring

© 著做權歸做者全部,轉載或內容合做請聯繫做者框架

img

spring-boot-starter-grpc 不一樣序列化方式性能測試及選型spring-boot

Spring Boot 2 集成log4j2日誌框架工具

Java面試通關要點彙總集之核心篇參考答案性能

Java面試通關要點彙總集之框架篇參考答案測試

Spring Security 實戰乾貨:如何保護用戶密碼編碼

Spring Boot RabbitMQ - 優先級隊列spa

本文由博客一文多發平臺 OpenWrite 發佈!

相關文章
相關標籤/搜索