Kotlin / kotlinx.html

Kotlin DSL for HTML
Apache License 2.0
1.63k stars 133 forks source link

Creating a simple layout #115

Closed decapo01 closed 5 years ago

decapo01 commented 5 years ago

Can I make a layout html page on the server side with this dsl?

example

fun layout(pageTitle: String, content: ?): String {
  return createHTMLDocument()
    .html {
      head {
        title { +pageTitle }
      }
      body {
        content
      }
}

fun homePageContent(): ? {
  ?
}

@GetMapping
@RequestBody
fun someSpringControllerMethos(): String {
  return layout("Home",homePageContent())
}
spand commented 5 years ago
content: FlowContent.() -> Unit

and do

      body {
        content()
      }
decapo01 commented 5 years ago

What goes in the body of homePageContent()

trying

fun homePageContent(): FlowContent.() -> Unit {

  return createHTMLDocument().div {
    h1 { +"hello" }
  }
}

or

fun homePageContent(): FlowContent.() -> Unit {

  return div {
    h1 { +"hello" }
  }
}

And neither are compiling

spand commented 5 years ago

FlowContent.() -> Unit is a function so return a lambda.

fun homePageContent(): FlowContent.() -> Unit = {
  div {
    h1 { +"hello" }
  }
}
decapo01 commented 5 years ago

This worked. For anyone else that stumbles upon this after searching, the full example is

fun layout(pageTitle: String, content: FlowContent.() -> Unit): String {
  return createHTMLDocument()
    .html {
      head {
        title { +pageTitle }
      }
      body {
        content()
      }
    }.serialize(false)
}

fun homePageContent(): FlowContent.() -> Unit = {
  div {
    h1 { +"hello" }
  }
}

@GetMapping
@RequestBody
fun someSpringControllerMethos(): String {
  return layout("Home",homePageContent())
}