spring boot 集成 Pebble,更优雅地输出变量

3,320 阅读1分钟

是什么

Pebble is a Java templating engine inspired by Twig. It features templates inheritance and easy-to-read syntax, ships with built-in autoescaping for security, and includes integrated support for internationalization.

Pebble是一款受Twig启发的Java模板引擎。它具有模板继承和易于阅读的语法,内置有安全的autoescaping,并包括对国际化的综合支持。

twig是一款非常流行的php的模板引擎,被众多php框架广泛应用。 语法同样在python django的模板引擎里可以看到。

为什么

Thymeleaf里我们的变量输出要写在标签里,这样感觉非常别扭

 <td th:text="${prod.name}">Oranges</td>

依赖

<dependency>
	<groupId>io.pebbletemplates</groupId>
   <artifactId>pebble-spring-boot-starter</artifactId>
	<version>3.0.5</version>
</dependency>

使用

 @RequestMapping("/hello")
    public String hello() {
        PebbleEngine engine = new PebbleEngine.Builder().build();
        PebbleTemplate compiledTemplate = engine.getTemplate("templates/home.html");
        Writer writer = new StringWriter();

        Map<String, Object> context = new HashMap<>();
        context.put("websiteTitle", "My First Website");
        context.put("content", "My Interesting Content");

        try {
            compiledTemplate.evaluate(writer, context);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String output = writer.toString();
        return output;
    }

添加模板文件

<!DOCTYPE html>
<h1>{{content}}</h1>
</html>

可以看到不用再像 Thymeleaf 那样,输出变量要写进标签属性里面。

静态资源

mvc:
    static-path-pattern: /static/**

更多资料

  1. 官方文档: https://pebbletemplates.io