Search code examples
templateskotlinpebble

Parse String template instead of file in Pebble Template Engine


Is it possible to use the Pebble Template Engine to build up a template from a String instead of having to provide a filename?

val engine = PebbleEngine.Builder().build()
val writer = StringWriter();
engine.getTemplate("test.html").evaluate(writer);

Instead of providing test.html, how would I for example provide a template in the following format?

val template = "Hello {{world}} - {{count}} - {{tf}}"

I'm currently on Pebble 2.2.1

<!-- Pebble -->
<dependency>
    <groupId>com.mitchellbosecke</groupId>
    <artifactId>pebble</artifactId>
    <version>2.2.1</version>
</dependency>

Solution based on the answers I've received:

val context = HashMap<String, Any>()
... 
val engine = PebbleEngine.Builder().loader(StringLoader()).build();
val writer = StringWriter();
engine.getTemplate(template).evaluate(writer, context);
println(writer.toString());

Solution

  • According to the tests, you just need to set the engine up with a StringLoader:

    val engine = PebbleEngine.Builder().loader(StringLoader()).build()