Use Thymeleaf API rendering templates to generate static pages

Thymeleaf is a new generation of Java template engine, its front-end developer-friendly syntax can be opened directly edit, Spring Boot also recommend you use it as a template engine, this article will demonstrate how to use the API to render it provides templates to generate static pages.

  1. Maven relies introduced
       <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
  1. Create templates, templates / example.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1 th:text="${name}">列表名称</h1>
    <ul>
        <li th:each="item: ${array}" th:text="${item}">条目</li>
    </ul>
</body>
</html>
  1. Using the API rendering templates to generate static pages
       //构造模板引擎
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setPrefix("templates/");//模板所在目录,相对于当前classloader的classpath。
        resolver.setSuffix(".html");//模板文件后缀
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(resolver);

        //构造上下文(Model)
        Context context = new Context();
        context.setVariable("name", "蔬菜列表");
        context.setVariable("array", new String[]{"土豆", "番茄", "白菜", "芹菜"});
        //渲染模板
        FileWriter write = new FileWriter("result.html");
        templateEngine.process("example", context, write);
        
  1. See results generated code is executed, result.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>蔬菜列表</h1>
    <ul>
        <li>土豆</li>
        <li>番茄</li>
        <li>白菜</li>
        <li>芹菜</li>
    </ul>
</body>
</html>

Guess you like

Origin blog.csdn.net/qq_21683643/article/details/94740251
Recommended