Skip to main content

Pebble extensions

Helpers for building custom Pebble extensions. Register them through InvirtPebbleConfig.extensions.

pebbleFunction​

Builds a PebbleFunction from a Kotlin lambda. The lambda receives a PebbleFunctionExecutionContext with the call arguments, current template, evaluation context and line number.

val currentUserFn = pebbleFunction("currentUser") {
request.principal as? User
}

val greetFn = pebbleFunction("greet", "name") {
"Hello, ${args["name"]}"
}

pebbleFilter​

Builds a PebbleFilter from a Kotlin lambda, the filter-side equivalent of pebbleFunction. The filtered value is the lambda's argument and the named arguments are on the receiver, along with the filter name and the template line a failure points at.

A null input reaches the lambda rather than short-circuiting to null: Pebble applies a filter to a null value too, and whether that is nothing to do or an error is the filter's own decision.

val markdownFilter = pebbleFilter("markdown") { input ->
input?.let { SafeString(MarkdownRenderer.toHtml(it as String)) }
}

val truncateFilter = pebbleFilter("truncate", "length") { input ->
val length = (args["length"] as? Number)?.toInt()
?: throw PebbleException(null, "Filter [$name] needs a length", lineNumber, template.name)
input?.toString()?.take(length)
}

pebbleFunctions​

Bundles one or more PebbleFunction instances into an Extension that can be passed to InvirtPebbleConfig.

Invirt.configure(
pebble = InvirtPebbleConfig(
extensions = listOf(
pebbleFunctions(currentUserFn, greetFn)
)
)
)

pebbleFilters​

The same for filters: bundles one or more PebbleFilter instances into an Extension.

Invirt.configure(
pebble = InvirtPebbleConfig(
extensions = listOf(
pebbleFilters(markdownFilter, truncateFilter)
)
)
)

EvaluationContext.request​

Inside a pebbleFunction block, context.request returns the http4k Request for the current render. A pre-built requestFunction and errorsFunction use this internally to expose request() and errors() in macros.