How to add comment for kotlin HTML DSL?

Is there a way to add html comment to kotlin HTML DSL like comment(“my comment”) that will result to <!-- my comment -->. Currently i’m using unsafe { +"""<!-- my comment -->"""} but it seems a bit off.

1 Like

You can add your own extension like

fun FlowContent.comment(text: String){
  unsafe { +"<!--$text-->"} 

Okay. Thank you very much.

You might want to ensure the text doesn’t contain -->, which would end the comment prematurely. (Or do something to escape it)

fun FlowContent.comment(text: String) {
    require(!text.contains("-->")) { "Comment text cannot contain '-->'" }
    unsafe { +"<!--$text-->" } 

Okay, thank you very much.

HTML DSL contains a comment function Tag::comment
And if you want it as a tag consumer define

inline fun <T, C : TagConsumer<T>> C.comment(s: String) = onTagComment(s)


fun main() {
    System.out.appendHTML().div { comment("foo") }
1 Like