Fork me on GitHub

Pebble Templates

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

Features

  • Rich set of built-in tags and filters
  • Template inheritance: extract common areas of your content in a single ‘layout’ and make your templates inherit this layout.
  • Extensible language: new tags, filters and functions can be added to Pebble very easily.

If you already know Twig, you can compare both engines in the compatibility matrix.

Basic Usage

First, add the following dependency to your pom.xml:

<dependency>
	<groupId>io.pebbletemplates</groupId>
	<artifactId>pebble</artifactId>
	<version>3.2.2</version>
</dependency>

Then create a template in your WEB-INF folder. Let's start with a base template that all other templates will inherit from, name it "base.html":

<html>
<head>
	<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
	<div id="content">
		{% block content %}{% endblock %}
	</div>
	<div id="footer">
		{% block footer %}
			Copyright 2018
		{% endblock %}
	</div>
</body>
</html>

Then create a template that extends base.html, call it "home.html":

{% extends "base.html" %}

{% block title %} Home {% endblock %}

{% block content %}
	<h1> Home </h1>
	<p> Welcome to my home page. My name is {{ name }}.</p>
{% endblock %}

Now we want to compile the template, and render it:

PebbleEngine engine = new PebbleEngine.Builder().build();
PebbleTemplate compiledTemplate = engine.getTemplate("home.html");

Map<String, Object> context = new HashMap<>();
context.put("name", "Mitchell");

Writer writer = new StringWriter();
compiledTemplate.evaluate(writer, context);

String output = writer.toString();

The output should result in the following:

<html>
<head>
	<title> Home </title>
</head>
<body>
	<div id="content">
		<h1> Home </h1>
	    <p> Welcome to my home page. My name is Mitchell.</p>
	</div>
	<div id="footer">
		Copyright 2018
	</div>
</body>
</html>

For more information on installation and configuration, see the installation guide.
For more information on basic usage, see the basic usage guide.
For Spring Boot integration, see the Spring Boot integration guide.