Skip to content

Instantly share code, notes, and snippets.

@bseib
Created November 30, 2024 15:36
Show Gist options
  • Save bseib/6f1d7b63d7acfbb47467a3775d2225d3 to your computer and use it in GitHub Desktop.
Save bseib/6f1d7b63d7acfbb47467a3775d2225d3 to your computer and use it in GitHub Desktop.
Javalin Pebble class for Pebble >= v3.2.x
package io.javalin.rendering.template
import io.javalin.http.Context
import io.javalin.rendering.FileRenderer
import io.javalin.rendering.util.RenderingDependency.PEBBLE
import io.javalin.util.DependencyUtil
import io.javalin.util.OptionalDependency
import io.pebbletemplates.pebble.PebbleEngine
import io.pebbletemplates.pebble.loader.ClasspathLoader
import java.io.StringWriter
class JavalinPebble32 @JvmOverloads constructor(
private var pebbleEngine: PebbleEngine = defaultPebbleEngine(),
) : FileRenderer {
private val pebble32 = object : OptionalDependency {
override val displayName = PEBBLE.displayName
override val testClass = "io.pebbletemplates.pebble.PebbleEngine"
override val groupId = PEBBLE.groupId
override val artifactId = PEBBLE.artifactId
override val version = "3.2.2"
}
init {
throwIfNotAvailable(pebble32)
}
private fun throwIfNotAvailable(dependency: OptionalDependency) {
if (!io.javalin.util.Util.classExists(dependency.testClass)) {
throw IllegalStateException(DependencyUtil.missingDependencyMessage(dependency))
}
}
override fun render(filePath: String, model: Map<String, Any?>, context: Context): String {
val compiledTemplate = pebbleEngine.getTemplate(filePath)
val stringWriter = StringWriter()
compiledTemplate.evaluate(stringWriter, model)
return stringWriter.toString()
}
companion object {
private fun defaultPebbleEngine() = PebbleEngine.Builder()
.loader(ClasspathLoader())
.strictVariables(false)
.build()
}
}
@bseib
Copy link
Author

bseib commented Nov 30, 2024

To use with a custom PebbleEngine construction:

    javalinConfig.fileRenderer(
        JavalinPebble32(
            PebbleEngine.Builder()
                .etc()
                .etc()
                .etc()
                .build()
        )
    )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment