Emit HTML with a DSL

This feature integrates with kotlinx.htmlto directly emit HTML using Chunked transfer encoding without having to keepmemory for the whole HTML.

This feature is defined in the class io.ktor.html.HtmlContent in the artifact io.ktor:ktor-html-builder:$ktor_version.

dependencies { implementation "io.ktor:ktor-html-builder:$ktor_version"}

dependencies { implementation("io.ktor:ktor-html-builder:$ktor_version")}

<project> … <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-html-builder</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies></project>

Installing

This feature doesn’t require installation.

Basic Usage

When generating the response, instead of calling the respond/respondText methods, you have to call ApplicationCall.respondHtml:

  1. call.respondHtml {
  2. head {
  3. title { +"Async World" }
  4. }
  5. body {
  6. h1(id = "title") {
  7. +"Title"
  8. }
  9. }
  10. }

For documentation about generating HTML using kotlinx.html, please check its wiki.

Templates & Layouts

In addition to plain HTML generation with the DSL, ktor exposes a simple typed templating engine.You can use it to generate complex layouts in a typed way. It is pretty simple, yet powerful:

  1. call.respondHtmlTemplate(MulticolumnTemplate()) {
  2. column1 {
  3. +"Hello, $name"
  4. }
  5. column2 {
  6. +"col2"
  7. }
  8. }
  9. class MulticolumnTemplate(val main: MainTemplate = MainTemplate()) : Template<HTML> {
  10. val column1 = Placeholder<FlowContent>()
  11. val column2 = Placeholder<FlowContent>()
  12. override fun HTML.apply() {
  13. insert(main) {
  14. menu {
  15. item { +"One" }
  16. item { +"Two" }
  17. }
  18. content {
  19. div("column") {
  20. insert(column1)
  21. }
  22. div("column") {
  23. insert(column2)
  24. }
  25. }
  26. }
  27. }
  28. }
  29. class MainTemplate : Template<HTML> {
  30. val content = Placeholder<HtmlBlockTag>()
  31. val menu = TemplatePlaceholder<MenuTemplate>()
  32. override fun HTML.apply() {
  33. head {
  34. title { +"Template" }
  35. }
  36. body {
  37. h1 {
  38. insert(content)
  39. }
  40. insert(MenuTemplate(), menu)
  41. }
  42. }
  43. }
  44. class MenuTemplate : Template<FlowContent> {
  45. val item = PlaceholderList<UL, FlowContent>()
  46. override fun FlowContent.apply() {
  47. if (!item.isEmpty()) {
  48. ul {
  49. each(item) {
  50. li {
  51. if (it.first) b {
  52. insert(it)
  53. } else {
  54. insert(it)
  55. }
  56. }
  57. }
  58. }
  59. }
  60. }
  61. }

You have to define classes implementing Template<TFlowContent>,overriding the TFlowContent.apply method and optionally definePlaceholder or TemplatePlaceholder properties just likein the example.

When generating the template with call.respondHtmlTemplate(MulticolumnTemplate()) { },you will get the template as receiver, and will be able to access the placeholdersdefined as properties in a typed way.