Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 562
Jan Vladimir Mostert Avatar asked Jan 07 '23 00:01

Jan Vladimir Mostert


1 Answers

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

val engine = PebbleEngine.Builder().loader(StringLoader()).build()
like image 57
tim_yates Avatar answered Jan 16 '23 01:01

tim_yates