Load Templates with Pebble
2 min read

Load Templates with Pebble

Load Templates with Pebble

Pebble is a templating engine. It looks particularly familiar to me because I have been using Django. You have access to blocks, include/import features, loops etc. This post is a simple exercise in loading some templates.


  • I've been using Eclipse IDE, but you can use whatever you prefer.

  • I've created a maven project and added pebble dependency:


The templates

I've created 3 templates in the resources folder of the project:


<!-- index.html -->

{% for entry in 1..5 %}
    {{ entry }}
{% endfor %}

<br />
<p>IT WORKS!</p>

<table style="width: 100%">
    {% for entry in 1..5 %}
      {% include "cell" with {"item":entry} %}
    {% endfor %}

{% for entry in 1..5 %}
    {% include "inner" with {"item":entry} %}
{% endfor %}
<br />



<td style="text-align: center;">{{item}}</td>

Note how the {{item}} parameter is taken from the loop in *index.html.


<li style="color:blue">{{item}}</li>

Note how the {{item}} is taken from the loop's with {"item":entry}.

Using the file loader

Pebble has a bunch of loaders, including the ability to go in cascade. It also has caching, but that's outside the current scope. For this exercise, we'll use the FileLoader directly:

import com.mitchellbosecke.pebble.loader.FileLoader;

// And in your method body:

FileLoader loader = new FileLoader();
PebbleEngine engine = new PebbleEngine.Builder()

The above will identify the templates location (by absolute path) and set the suffix of templates. Then, we can load the template:

PebbleTemplate compiledTemplate = engine.getTemplate("index");

In order to populate the template's contents ({{}}), we create a dictionary with the names/objects:

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

Then, we can evaluate the template and print out the result

compiledTemplate.evaluate(writer, context);
String output = writer.toString();

This is very simple.

Note: The pebble API calls throw PebbleException and you'll need to catch them. You'll also need to catch the IOExceptions thrown by the streaming API.