在Spring Boot中集成Pebble模板引擎的实现疑问
别发愁啦!在Spring Boot里集成Pebble模板引擎其实没你想的那么复杂,我帮你一步步理清楚:
在Spring Boot中集成Pebble模板引擎的完整步骤
1. 先搞定Maven依赖
Pebble专门提供了Spring Boot Starter,完全支持自动配置,和Thymeleaf、Mustache的使用逻辑一致,不用手动写一堆配置类。直接在你的pom.xml里加这段依赖就行:
<dependency> <groupId>io.pebbletemplates</groupId> <artifactId>pebble-spring-boot-starter</artifactId> <version>3.2.0</version> <!-- 可以替换成最新的稳定版本 --> </dependency>
2. 自定义配置(可选)
如果需要调整Pebble的默认行为,比如模板后缀、缓存开关、模板存放路径这些,直接在application.properties或者application.yml里加配置项就好,举几个常用的例子:
# 把模板后缀改成.html(默认是.pebble) pebble.suffix=.html # 开发环境一定要关缓存,不然改了模板看不到效果 pebble.cache=false # 把模板放在templates下的pebble子目录里(默认是classpath:/templates/) pebble.prefix=classpath:/templates/pebble/
要是你完全用默认配置,这一步直接跳过就行。
3. 写控制器和模板
这部分和用其他模板引擎一模一样,控制器返回模板名称,模板里用Pebble的语法渲染数据:
比如控制器代码:
@Controller public class HomeController { @GetMapping("/") public String home(Model model) { model.addAttribute("greeting", "Hello Pebble in Spring Boot!"); return "home"; // 对应templates/home.pebble(用默认后缀的话) } }
然后在src/main/resources/templates/下创建home.pebble模板:
<!DOCTYPE html> <html> <head> <title>Pebble Demo</title> </head> <body> <h1>{{ greeting }}</h1> </body> </html>
关于Spring MVC和Spring Boot的区别
你提到官网指南是针对Spring MVC的,其实Spring Boot就是把Spring MVC的手动配置都封装成了自动配置逻辑。那些Spring MVC里需要手动注册PebbleViewResolver、PebbleEngine的步骤,Spring Boot Starter都帮你搞定了,你完全不用操心这些底层配置,专注写业务和模板就行。
小提醒
- 要是模板找不到,先检查
pebble.prefix配置和文件路径对不对 - 开发环境记得关缓存,不然改了模板还要重启应用才能看到效果
- 注意版本兼容:Spring Boot 3.x对应Pebble 3.x版本,尽量匹配上避免踩坑
内容的提问来源于stack exchange,提问作者Ricardo Raz




