美文网首页首页推荐程序员
使用Thymeleaf API渲染模板生成静态页面

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

作者: 简单的土豆 | 来源:发表于2017-04-18 17:13 被阅读6070次

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

引入Maven依赖

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>

创建模板,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>

使用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);

执行上述代码查看生成结果,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>

相关文章

网友评论

    本文标题:使用Thymeleaf API渲染模板生成静态页面

    本文链接:https://www.haomeiwen.com/subject/clfqzttx.html