在Pebble Template Engine中解析字符串模板而不是文件

时间:2016-05-26 09:38:17

标签: templates kotlin pebble

是否可以使用Pebble Template Engine从String构建模板而不必提供文件名?

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

我不是提供test.html,而是以下列格式提供模板?

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

我目前正在使用Pebble 2.2.1

<!-- Pebble -->
<dependency>
    <groupId>com.mitchellbosecke</groupId>
    <artifactId>pebble</artifactId>
    <version>2.2.1</version>
</dependency>
根据我收到的答案

解决方案

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

2 个答案:

答案 0 :(得分:3)

根据to the tests,您只需要使用StringLoader设置引擎:

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

答案 1 :(得分:2)

您需要向引擎提供StringLoader,如下所示:

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>