4

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());
Jan Vladimir Mostert
  • 12,380
  • 15
  • 80
  • 137

2 Answers2

6

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

val engine = PebbleEngine.Builder().loader(StringLoader()).build()
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • just as the Pebble repo finished checking out you answered, nooice! – Jan Vladimir Mostert May 26 '16 at 10:17
  • This loader is not intended to be used in a production system; it is primarily for testing and debugging. Many tags do not work when using this loader, such as "extends", "imports", "include". – erdem Jul 22 '22 at 15:09
4

You need to supply a StringLoader to the engine like so:

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

val writer = StringWriter()
engine.getTemplate("<p>{{name}}</p>").evaluate(writer, mapOf("name" to "Stack Overflow"))
val result = writer.toString() // "<p>Stack Overflow</p>
miensol
  • 39,733
  • 7
  • 116
  • 112