Skip to content

Instantly share code, notes, and snippets.

@wowselim
Created May 10, 2023 10:29
Show Gist options
  • Save wowselim/8903927828c1e4a8d43649af499fe7bb to your computer and use it in GitHub Desktop.
Save wowselim/8903927828c1e4a8d43649af499fe7bb to your computer and use it in GitHub Desktop.
Vert.x + Kotlin + JTE + HTMX
plugins {
id("gg.jte.gradle") version "2.2.2"
}
jte {
precompile()
}
tasks.withType<ProcessResources> {
dependsOn(tasks.withType<CompileSass>())
exclude("**/.gitkeep")
}
tasks.jar {
dependsOn(tasks.precompileJte)
from(fileTree("jte-classes")) {
include("**/*.class")
include("**/*.bin") // Only required for binary templates
}
}
// templates in /src/main/jte
override val templateEngine: TemplateEngine by lazy {
val path = Path.of("src", "main", "jte")
TemplateEngine.create(DirectoryCodeResolver(path), ContentType.Html)
.apply { setBinaryStaticContent(true) }
}
interface TemplateEngineProvider {
val templateEngine: TemplateEngine
}
context(TemplateEngineProvider)
suspend fun RoutingContext.endWithHTMX(
templateName: String,
model: Map<String, Any> = emptyMap(),
) {
val enrichedModel = model + mapOf("htmx" to isHTMXRequest)
val output = Utf8ByteOutput()
templateEngine.render("$templateName.jte", enrichedModel, output)
response()
.putHeader(HttpHeaders.CONTENT_TYPE, "text/html")
.end(output.toBuffer())
.await()
}
private fun Utf8ByteOutput.toBuffer(): Buffer {
val buffer = Buffer.buffer(contentLength)
writeTo(buffer::appendBytes)
return buffer
}
private val HTMX_HEADER = HttpHeaders.createOptimized("HX-Request")
private val RoutingContext.isHTMXRequest
get() = request().getHeader(HTMX_HEADER).toBoolean()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment