io.javalin.rendering.template.JavalinThymeleaf.kt Maven / Gradle / Ivy
/*
* 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 io.javalin.http.Context
import io.javalin.rendering.FileRenderer
import io.javalin.rendering.JavalinRenderer
import io.javalin.rendering.util.RenderingDependency.THYMELEAF
import io.javalin.rendering.util.Util
import org.thymeleaf.TemplateEngine
import org.thymeleaf.context.WebContext
import org.thymeleaf.templatemode.TemplateMode
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
import org.thymeleaf.web.servlet.JakartaServletWebApplication
class JavalinThymeleaf @JvmOverloads constructor(
private var templateEngine: TemplateEngine = defaultThymeLeafEngine()
) : FileRenderer {
override fun render(filePath: String, model: Map, ctx: Context): String {
// ctx.req.servletContext that is passed to buildApplication has to match ctx.req.servletContext passed into
// buildExchange. (application.servletContext === ctx.req.servletContext)
val application = JakartaServletWebApplication.buildApplication(ctx.req().servletContext)
val webExchange = application.buildExchange(ctx.req(), ctx.res())
val context = WebContext(webExchange, webExchange.locale, model)
return templateEngine.process(filePath, context)
}
companion object {
val extensions = arrayOf(".html", ".tl", ".thyme", ".thymeleaf")
@JvmStatic
@JvmOverloads
fun init(templateEngine: TemplateEngine? = null) {
Util.throwIfNotAvailable(THYMELEAF)
JavalinRenderer.register(JavalinThymeleaf(templateEngine ?: defaultThymeLeafEngine()), *extensions)
}
private fun defaultThymeLeafEngine() = TemplateEngine().apply {
setTemplateResolver(ClassLoaderTemplateResolver().apply {
templateMode = TemplateMode.HTML
})
}
}
class Loader : JavalinRenderer.FileRendererLoader {
override fun load() = if (!JavalinRenderer.hasRenderer(*extensions) && THYMELEAF.exists()) init() else Unit
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy