All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.javalin.rendering.template.JavalinPebble.kt Maven / Gradle / Ivy

There is a newer version: 6.4.0
Show newest version
/*
 * Javalin - https://javalin.io
 * Copyright 2017 David Åse
 * Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
 */

package io.javalin.rendering.template

import com.mitchellbosecke.pebble.PebbleEngine
import com.mitchellbosecke.pebble.loader.ClasspathLoader
import io.javalin.http.Context
import io.javalin.rendering.FileRenderer
import io.javalin.rendering.JavalinRenderer
import io.javalin.rendering.util.RenderingDependency.PEBBLE
import io.javalin.rendering.util.Util
import java.io.StringWriter

class JavalinPebble @JvmOverloads constructor(
    private var pebbleEngine: PebbleEngine = defaultPebbleEngine()
) : FileRenderer {

    override fun render(filePath: String, model: Map, ctx: Context): String {
        val compiledTemplate = pebbleEngine.getTemplate(filePath)
        val stringWriter = StringWriter()
        compiledTemplate.evaluate(stringWriter, model)
        return stringWriter.toString()
    }

    companion object {
        val extensions = arrayOf(".peb", ".pebble")

        @JvmStatic
        @JvmOverloads
        fun init(pebbleEngine: PebbleEngine? = null) {
            Util.throwIfNotAvailable(PEBBLE)
            JavalinRenderer.register(JavalinPebble(pebbleEngine ?: defaultPebbleEngine()), *extensions)
        }

        private fun defaultPebbleEngine() = PebbleEngine.Builder()
            .loader(ClasspathLoader())
            .strictVariables(false)
            .build()
    }

    class Loader : JavalinRenderer.FileRendererLoader {
        override fun load() = if (!JavalinRenderer.hasRenderer(*extensions) && PEBBLE.exists()) init() else Unit
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy