Use Thymeleaf dynamic rendering HTML

1, adding a dependency

  <!-- Thymeleaf 模板引擎 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.9.RELEASE</version>
        </dependency>复制代码

2, the encoding tools 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);
    }

}复制代码

3, the test template engine

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

}复制代码

Console output

Thymeleaf 渲染 HTML ---- Anoy

Related Documents

Thymeleaf template syntax

© copyright reserved by the authors, reprint please contact the author or content partners

img

Spring-Boot-Starter-GRPC different serialization performance testing and selection

the Spring integration log4j2日志框架the Boot 2

core Java chapter sets off point summary of the interview on Answers

framework for Java interview clearance papers set of reference points are summarized answers

the Spring Security combat dry goods: how to protect user passwords

the Spring the Boot RabbitMQ - priority queue

This article from the blog article multiple platforms OpenWrite release!

Guess you like

Origin juejin.im/post/5daf2b70518825502a4460d7