org.http4k.template.ThymeleafTemplates.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of http4k-template-thymeleaf Show documentation
Show all versions of http4k-template-thymeleaf Show documentation
Http4k Thymeleaf templating support
package org.http4k.template
import org.thymeleaf.ITemplateEngine
import org.thymeleaf.TemplateEngine
import org.thymeleaf.cache.StandardCacheManager
import org.thymeleaf.context.Context
import org.thymeleaf.exceptions.TemplateInputException
import org.thymeleaf.templatemode.TemplateMode
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
import org.thymeleaf.templateresolver.FileTemplateResolver
import java.io.FileNotFoundException
class ThymeleafTemplates(private val configure: (TemplateEngine) -> TemplateEngine = { it },
private val classLoader: ClassLoader = ClassLoader.getSystemClassLoader()) : Templates {
override fun CachingClasspath(baseClasspathPackage: String): TemplateRenderer =
ThymeleafTemplateRenderer(configure(TemplateEngine().apply {
setTemplateResolver(ClassLoaderTemplateResolver(classLoader).apply {
templateMode = TemplateMode.HTML
prefix = if (baseClasspathPackage.isEmpty()) "" else baseClasspathPackage.replace('.', '/') + "/"
suffix = ".html"
})
}))
override fun Caching(baseTemplateDir: String): TemplateRenderer =
ThymeleafTemplateRenderer(configure(TemplateEngine().apply {
setTemplateResolver(FileTemplateResolver().apply {
templateMode = TemplateMode.HTML
prefix = "$baseTemplateDir/"
suffix = ".html"
})
}))
override fun HotReload(baseTemplateDir: String): TemplateRenderer =
ThymeleafTemplateRenderer(configure(TemplateEngine().apply {
cacheManager = StandardCacheManager().apply {
templateCacheMaxSize = 0
}
setTemplateResolver(FileTemplateResolver().apply {
templateMode = TemplateMode.HTML
prefix = "$baseTemplateDir/"
suffix = ".html"
})
}))
private class ThymeleafTemplateRenderer(private val engine: ITemplateEngine) : TemplateRenderer {
override fun invoke(viewModel: ViewModel): String = try {
engine.process(viewModel.template(), Context().apply {
setVariable("model", viewModel)
})
} catch (e: TemplateInputException) {
when (e.cause) {
is FileNotFoundException -> throw ViewNotFound(viewModel)
else -> throw e
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy