Estimate project
← All posts

Ktor templating: Pebble compared with HTML DSL

A look at what you gain and lose with classic HTML-based templates versus Kotlin's type-safe DSL when rendering on the server, with a focus on readability, extensibility, and everyday usability of each approach.

5 min read
KotlinHTMLKtorKotlinServerSide

Over the past months, Server Side Rendering (SSR) has returned in a big way. Stepping back from JSON as the means of talking to the front-end has felt genuinely refreshing. You can pick from many templating languages, and once you know one of them, moving to another is usually easy. Not long ago, I came across one I wanted to try out – HTML DSL, a kotlinx.html integration shipped with Ktor, a Kotlin framework for creating asynchronous client and server applications. It takes a different angle on templating: you write plain HTML in Kotlin, interpolate variables into views, and assemble complex layouts. I think extensibility is among HTML’s greatest strengths, and I have doubts about whether type-safety will get along with it – so let’s dig in and compare HTML DSL with Pebble templates, a more conventional templating language!

Base page with Pebble

My idea was to compare the two using a sample rolodex app for managing contacts, styled lightly with Pico. Let’s go one step at a time, though, and begin with nothing meaningful inside <body>. Here, the pebble template is exactly the same as plain HTML:

<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
  <link rel="stylesheet" href="/static/css/main.css">
  <meta charset="UTF-8"/>
  <title>Pebble vs HTML DSL</title>
</head>
<body>
<main class="container">
  <h1>It works 🚀!</h1>
</main>
</body>
</html>

Nothing unusual here, apart from the custom data-themeargument from Pico in the <html> tag.

Next comes extracting the base page. Some form of inheritance or composition is a must-have when generating an HTML page on the server – it lets you pull out a part of the page and inject the actual content into it later. In Pebble, this is achieved with tags (not the same as regular HTML tags):

{# base.peb #}

<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
  <link rel="stylesheet" href="/static/css/main.css">
  <meta charset="UTF-8"/>
  <title>Pebble vs HTML DSL</title>
  <style>
  </style>
</head>
<body>
<main class="container">
    {% block content %}{% endblock %}
</main>
</body>
</html>

We can then reuse it to render the index page like this:

{# index.peb #}
{% extends "base.peb" %}

{% block content %}
<h1>It works 🚀!</h1>
{% endblock %}

Base page with HTML DSL and descoping

With a feel for how the base page works in a standard templating language, we can move on to HTML DSL. After going through the docs and looking into custom parameters, the Kotlin routing code equivalent to the basic index.peb looks as follows:

fun Application.configureRouting() {
  routing { 
    staticResources("/static", "static") {
      extensions("css")
      preCompressed(CompressedFileType.GZIP)
    }
    get("/") {
      call.respondHtml(HttpStatusCode.OK) {
        lang = "en"
        attributes["data-theme"] = "light"
        head {
          link {
            href = "https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css"
            rel = "stylesheet"
          }
          link {
            href = "/static/css/main.css"
            rel = "stylesheet"
          }
          meta {
            charset = "UTF-8"
          }
          title {
            +"Pebble vs HTML DSL"
          }
        }
        body {
          main {
            classes = linkedSetOf("container")
            h1 {
              +"It works 🚀!"
            }
          }
        }
      }
    }
  }
}

This is nothing like regular HTML! Is that an advantage, though? Honestly, I don’t think so, and here are my problems with the DSL approach:

  • Even for a page this simple, it’s not instantly clear which pieces of code correspond to which parts of the HTML. That can make debugging JavaScript code harder than it needs to be.
  • Since the code doesn’t look like HTML, people unfamiliar with Kotlin will struggle to work on the front-end side of the project.
  • That difference has another downside – HTML component libraries can’t be used with this approach unless a non-trivial amount of effort goes into translating them into the DSL
  • Using a Set for the class attribute may seem like a neat way to avoid duplicates, but it can have unexpected side effects, since it may break your attribute selectors; for example, [class="class1 class2"] differs from [class="class2 class1"]. As a rule, linkedSetOf should be used
  • As I mentioned at the start, extensibility is one of HTML’s design principles.I doubted that strict type-safety could hold up in every case, and indeed, it broke in the very first tag, when we wanted to set Pico’s theme with a data attribute. Libraries also frequently rely on other custom attributes.

Next, let’s extract the base portion of this code into a separate method of the HTML class so that it becomes part of our DSL.

object Templates {
    fun HTML.base(content: FlowContent.() -> Unit) {
        lang = "en"
        attributes["data-theme"] = "light"

        ...

        body {
            main {
                classes = setOf("container")
                content()
            }
        }
    }
}

//Application.configureRouting
get("/") {
  call.respondHtml(HttpStatusCode.OK) {
    base {
      h1 {
        +"It works 🚀!"
      }
    }
  }
}

This refactoring required a bit more Kotlin know-how, but the effort shouldn’t differ much from one case to another.

When I began writing this article, I had an ambitious plan – comparing Pebble and HTML DSL using a simple rolodex app. Sadly, the DSL made even a read-only app hard to read, so I chose not to cover the rest in this post. For the finished read-only version, the line count comes to 75 vs 128, with Pebble being the shorter one.

Conclusion

I can see a few upsides of the HTML DSL:

  • Full support in IDEA, since it’s simply Kotlin code
  • It’s the only templating option in Ktor that works with a native server
  • It works right away once the dependency is added to the build
  • It avoids the annoying restriction of template tags, which usually have to sit on a single line

Personally, though, I won’t reach for it again any time soon – I find that, compared with established template languages, it makes building web apps more complicated than necessary.