https://kotlinlang.org logo
#http4k
Title
m

Mikael Ståldal

07/02/2023, 12:58 PM
Has anyone used http4k (server) together with HTMX?
d

dave

07/02/2023, 1:06 PM
We actually haven't, but we were recently looking for ways in which we might be able to provide support (if any was required) for it. AFAICT, there is no reason why they shouldn't slot together perfectly with the tools we already have. Of course, if anyone has used the 2 together and has suggestions as to what type of thing might be a good integration then please let us know here! 🙃
m

Mikael Ståldal

07/03/2023, 5:18 PM
Not sure I am fully satisfied though. It would be nice to be able to use different templates for the same model (for view vs. edit views), and also a template without any model (for the index page, which uses Thymeleaf's `th:replace` feature to include a snippet from another template file).
d

dave

07/04/2023, 8:13 AM
Well this is open source. Have a go at something (which doesn't break backwards if possible) and PR it 🙃
m

Mikael Ståldal

07/04/2023, 8:14 AM
Yes, I am just trying to figure out how (thinking out loud...).
My current workaround is to use Kotlin's delegation feature:
Copy code
interface Person {
    val firstName: String
    val lastName: String
    val email: String
}

data class PersonData(override val firstName: String, override val lastName: String, override val email: String) : Person

data class ViewPerson(val personData: PersonData) : HtmlViewModel(), Person by personData
data class EditPerson(val personData: PersonData) : HtmlViewModel(), Person by personData
(This would probably be horrible in Java...)
Maybe something like this:
Copy code
interface ViewModel {
    fun template(): String = javaClass.name.replace('.', '/')
    fun model(): Any? = this
}

data class ViewWithModel(val template: String, val model: Any? = null) : ViewModel {
    override fun template() = template
    override fun model() = model
}
and then change the uses of
ViewModel
in all template implementations to use
this.model()
instead of
this
. Then I can do like this:
Copy code
"/" bind Method.GET to {
            Response(OK).with(htmlLens of ViewWithModel("index"))
        },
        "/person/view" bind Method.GET to {
            Response(OK).with(htmlLens of ViewWithModel("ViewPerson", person))
        },
        "/person/edit" bind Method.GET to {
            Response(OK).with(htmlLens of ViewWithModel("EditPerson", person))
        },
I'll try to make a PR of this tomorrow (no time today).
(And it will still be possible to use
ViewModel
as before, and mix the two.)
Another attempt with kotlinx.html instead of Thymeleaf templates: https://github.com/mikaelstaldal/htmx-http4k-dsl
24 Views