使用Thymeleaf API渲染模板生成静态页面

Thymeleaf 是新一代的Java模板引擎,它的语法对前端开发者友好可直接打开编辑,Spring Boot也建议使用它作为你的模板引擎,本文将演示如何使用它提供的API来渲染模板生成静态页面。

  1. 引入Maven依赖
       <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
  1. 创建模板,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. 使用API渲染模板生成静态页面
       //构造模板引擎
        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. 执行上述代码查看生成结果,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>

猜你喜欢

转载自blog.csdn.net/qq_21683643/article/details/94740251