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.

Prerequisites

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

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

    <dependency>
    <groupId>com.mitchellbosecke</groupId>
    <artifactId>pebble</artifactId>
    <version>2.1.0</version>
    </dependency>
    

The templates

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

index.html

<!-- index.html -->
<html>
<head>
</head>
<h1>{{websiteTitle}}</h1>
<p>{{content}}</p>

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

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

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

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

</html>

cell.html

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

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

inner.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();
loader.setPrefix("path/to/resourcesresources");
loader.setSuffix(".html");
PebbleEngine engine = new PebbleEngine.Builder()
    .loader(loader)
    .build();

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();
System.out.println(output);

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.