Why I Love Using Pebble Templates with Spring Boot?
Tags: springboot, templateengine, pebble, webdev
Published: 2023-10-06 03:14:22

As a Java backend engineer with 6 years of experience working with Spring Boot, I have had the chance to work with different template engines over the years. Recently, I have fallen in love with using Pebble as my go-to template engine for Spring Boot applications. In this article, I'll explain what Pebble is, why I enjoy using it so much, and how to configure it in a Spring Boot 2 application. I'll start with why first!

## Why I Love Using Pebble

After using various template engines over the years such as Thymeleaf, FreeMarker, and JSPs, Pebble has become my favorite for several reasons:

- **Simple and familiar syntax** - Pebble's syntax is easy to learn and feels familiar, even for non-Java developers. This improves productivity.
- **Avoid verbosity** - Pebble templates are concise and avoid verbose markup. This keeps code clean and maintainable.
- **Seamless integration** - Pebble integrates smoothly with Spring Boot for managing templates and rendering views.
- **Secure by default** - The sandboxed execution and auto-escaping make Pebble secure against XSS attacks.
- **Easy to extend** - Writing custom extensions is straightforward with Pebble. I can add functionality as needed.
- **Active development** - Pebble is under active development with a growing community behind it.
- **Speed** - Pebble templates compile to Java code that executes quickly.

![Pebble templates compile to Java code that executes quickly](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tnpf0smgbis31yienudf.png)

Overall, I have found Pebble to be a joy to work with. It makes building web UIs simple and productive.

## What is Pebble?

Pebble is an open source Java template engine inspired by Twig from PHP. It is modern, lightweight, and secure. Some of the key features of Pebble include:

- Simple syntax - Pebble uses a straightforward syntax without too much "magic", making templates easy to write and understand.
- Sandboxed execution - Templates are executed in a sandboxed environment for security.
- Extensions - Pebble supports extensions to add custom tags, filters, tests, and more.
- Caching - Templates get cached after compilation for improved performance.
- Inheritance - Template inheritance allows better code reuse.
- Easy escaping - Output is escaped by default to prevent XSS vulnerabilities.

## Using Pebble with Spring Boot
It is easy to get started using Pebble templates in a Spring Boot 2 application. Here are the basic steps:

**1. Add the Pebble dependency to your `pom.xml`:**

```xml
<dependency>
  <groupId>io.pebbletemplates</groupId>
  <artifactId>pebble-spring-boot-starter</artifactId>
  <version>3.2.1</version>
</dependency>
```

Or using gradle:

```
//pebble template engine
implementation group: 'io.pebbletemplates', name: 'pebble-spring-boot-starter', version: '3.2.1'
```

**2. Configure Spring Boot to use Pebble as the template engine:**
```properties
pebble.suffix=.peb.html
pebble.cache=false
// disable somethings
spring.thymeleaf.enabled=false 
spring.freemarker.enabled=false 
spring.groovy.template.enabled=false
```

**3. Put your Pebble templates in `src/main/resources/templates`**

![Create index.html](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9151swa8w9d4ue68ij2m.png)

**4. Load and render templates from your controllers**

```Java
@Controller
public class HomeController {

  @GetMapping("/")
  public String index(Model model) {
    model.addAttribute("message", "Hello World!");
    return "index"; // will render src/main/resources/templates/index.peb.htm
  }
}
```

## Pebble Extension
One of the great features of Pebble is the ability to create custom functions to extend the template engine. This allows adding application-specific logic right in the template layer.

A common use case is to format dates in a customized way. While Pebble does provide some default date formatting filters like date, you often need more control.

We can create a custom date formatting function like this:

```Java
@Configuration
public class PebbleConfig {

  @Bean
  public PebbleTemplateEngine pebbleTemplateEngine() {
    PebbleEngine engine = new PebbleEngine.Builder().build();
    engine.addExtension(new AbstractExtension() {

      @Override
      public Map<String, Function> getFunctions() {
        return Map.of("formatDate", new FormatDateFunction());
      }

    });
    return new PebbleTemplateEngine(engine);
  }

  private class FormatDateFunction implements Function {

    @Override
    public List<String> getArgumentNames() {
      return List.of("date", "pattern");
    }

    @Override
    public Object execute(Map<String, Object> args) {
      Date date = (Date) args.get("date");
      String pattern = (String) args.get("pattern");
      SimpleDateFormat sdf = new SimpleDateFormat(pattern); 
      return sdf.format(date);
    }
    
  }
  
}
```

This allows us to call the custom formatDate function from any Pebble template:

```
{{ formatDate(article.date, "MMMM dd, yyyy") }}
```
The ability to create application-specific functions like this without having to implement a tag library makes Pebble extremely flexible. Custom date formatting is just one example of the many possibilities.

That's it! With just a bit of configuration, you can start using Pebble's simple yet powerful templating capabilities in your Spring Boot web application.

## Conclusion

In my experience, Pebble provides an excellent blend of simplicity, security, performance, and extensibility as a template engine for Java web applications. If you are looking for a modern alternative to JSPs and Thymeleaf, I highly recommend giving Pebble a try in your next Spring Boot project. Its familiar syntax, seamless integration, and active community make it a joy to work with.

**Referral:** 
- Pebble Template Engine: https://pebbletemplates.io/
- Template Benchmark: https://github.com/mbosecke/template-benchmark

**Read more:** 
- [Power Your Web Applications: Top 10 Modern CSS Frameworks for Backend Engineers](https://dev.to/jackynote/power-your-web-applications-top-10-modern-css-frameworks-for-backend-engineers-ale)
- [Exploring the Top Template Engine for Spring Boot 3 Web Application in 2023](https://dev.to/jackynote/exploring-the-top-template-engine-for-spring-boot-3-web-application-in-2023-63e)