Load Templates with Pebble

Posted by in Software, Tutorial

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:

The templates

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

index.html

cell.html

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

inner.html

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:

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

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

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

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.


A little experiment: If you find this post and ad below useful, please check the ad out :-)