Text and HTML templates

suggest change

A template mixes fixed text with values filled in at run time. Emails, reports, config files, code generators and web pages are all built this way.

In Kotlin you have three main options:

This article covers:

The $name and ${expr} syntax is covered in String Templates, and the DSL techniques behind kotlinx.html are covered in Type-Safe Builders and DSL Building.

Plain text with string templates

For text whose shape is fixed in code, string templates are the simplest and fastest option. Use a raw string with trimIndent() when the layout matters, and buildString when you need loops or conditionals:

data class Item(val name: String, val qty: Int, val price: Double)

fun receipt(customer: String, items: List<Item>): String = buildString {
    appendLine("Receipt for $customer")
    appendLine("-".repeat(32))
    for (item in items) {
        val total = item.qty * item.price
        appendLine("%-18s %2d x %6.2f".format(item.name, item.qty, item.price))
        if (item.qty > 1) appendLine("%32s".format("= %.2f".format(total)))
    }
    appendLine("-".repeat(32))
    append("Total: %.2f".format(items.sumOf { it.qty * it.price }))
}

fun welcomeEmail(name: String, days: Int) = """
    Hi $name,

    Your trial ends in $days ${if (days == 1) "day" else "days"}.
    Questions? Reply to this email.
    """.trimIndent()

fun main() {
    println(welcomeEmail("Ann", 3))
    println()
    println(receipt("Bob", listOf(Item("Coffee", 2, 3.5), Item("Bagel", 1, 2.25))))
}
Hi Ann,

Your trial ends in 3 days.
Questions? Reply to this email.

Receipt for Bob
--------------------------------
Coffee              2 x   3.50
                          = 7.00
Bagel               1 x   2.25
--------------------------------
Total: 9.25

trimIndent() removes the common leading whitespace and the first and last blank lines, so the template can be indented to match the surrounding code. String.format handles column alignment and number formatting. The if expression inside ${...} handles small variations such as plurals.

This approach has two limits. Templates are compiled into the program, so changing the wording means a new build. And string templates don't escape anything, which is fine for plain text but dangerous for HTML (see below).

User-editable templates with placeholders

When the template text comes from configuration, a database or a translation file, Kotlin string templates can't help: $name is resolved at compile time, not when the string is read from a file. For simple cases a regex-based substitution is enough:

val placeholder = Regex("""\{(\w+)}""")

fun render(template: String, values: Map<String, Any?>): String =
    placeholder.replace(template) { m ->
        val key = m.groupValues[1]
        values[key]?.toString() ?: error("missing value for {$key}")
    }

fun main() {
    // template text comes from config, a database or a translator, not from code
    val tpl = "Hello {name}, you have {count} new messages."
    println(render(tpl, mapOf("name" to "Ann", "count" to 5)))

    // the lambda result is inserted as is: "$1" is not treated as a group reference
    println(render("Price: {price}", mapOf("price" to "$1 off")))

    try {
        render(tpl, mapOf("name" to "Bob"))
    } catch (e: IllegalStateException) {
        println("error: ${e.message}")
    }
}
Hello Ann, you have 5 new messages.
Price: $1 off
error: missing value for {count}

Two details matter here:

If templates need loops or conditionals, use a real template engine rather than growing this function.

Escaping HTML

Text inserted into HTML must be escaped, or user input becomes markup. This is the root cause of cross-site scripting (XSS):

fun String.escapeHtml(): String = buildString(length) {
    for (c in this@escapeHtml) {
        when (c) {
            '&' -> append("&amp;")
            '<' -> append("&lt;")
            '>' -> append("&gt;")
            '"' -> append("&quot;")
            '\'' -> append("&#39;")
            else -> append(c)
        }
    }
}

data class Comment(val author: String, val text: String)

fun commentHtml(c: Comment) =
    """<div class="comment"><b>${c.author.escapeHtml()}</b>: ${c.text.escapeHtml()}</div>"""

fun main() {
    val evil = Comment("mallory\" onmouseover=\"alert(1)", "<script>steal(document.cookie)</script>")

    // wrong: user input goes into the markup as is
    println("""<div class="comment" title="${evil.author}">${evil.text}</div>""")

    // right: escape every value at the point where it enters HTML
    println(commentHtml(evil))
}
<div class="comment" title="mallory" onmouseover="alert(1)"><script>steal(document.cookie)</script></div>
<div class="comment"><b>mallory&quot; onmouseover=&quot;alert(1)</b>: &lt;script&gt;steal(document.cookie)&lt;/script&gt;</div>

The first line lets a malicious user name add an onmouseover handler and run a script. The second line escapes the same data, so the browser shows it as text.

Escaping by hand works, but it's easy to forget one value. Prefer tools that escape by default: kotlinx.html escapes all text and attribute values, and FreeMarker (.ftlh), Mustache ({{x}}) and Pebble escape output unless you explicitly opt out.

HTML escaping isn't enough for every context. A value placed inside a URL needs URL encoding (URLEncoder.encode), and a value inside a <script> block or a style attribute needs JavaScript or CSS escaping. Avoid putting user data in those places at all.

kotlinx.html

kotlinx.html is JetBrains' DSL for building HTML. Each tag is a function that takes a lambda, attributes are named parameters or properties, and +"text" adds an escaped text node.

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-html-jvm:0.12.0")
}

Building a document

createHTML() returns a builder that produces a String. Ordinary Kotlin if, for and when take the place of template directives:

import kotlinx.html.*
import kotlinx.html.stream.createHTML
import java.net.URLEncoder

data class Book(val title: String, val author: String, val year: Int)

fun main() {
    val books = listOf(
        Book("Kotlin in Action", "Jemerov & Isakova", 2017),
        Book("<Effective> Java", "Bloch", 2018),
    )

    val html = createHTML().html {
        head {
            meta(charset = "utf-8")
            title("Reading list")
        }
        body {
            h1 { +"Reading list" }
            if (books.isEmpty()) {
                p { +"Nothing yet." }
            } else {
                ul("books") {
                    for (b in books) {
                        li {
                            val link = "/books?title=" + URLEncoder.encode(b.title, Charsets.UTF_8)
                            a(href = link) { +b.title }
                            +" by ${b.author} (${b.year})"
                        }
                    }
                }
            }
        }
    }
    println(html)
}
<html>
  <head>
    <meta charset="utf-8">
    <title>Reading list</title>
  </head>
  <body>
    <h1>Reading list</h1>
    <ul class="books">
      <li><a href="/books?title=Kotlin+in+Action">Kotlin in Action</a> by Jemerov &amp; Isakova (2017)</li>
      <li><a href="/books?title=%3CEffective%3E+Java">&lt;Effective&gt; Java</a> by Bloch (2018)</li>
    </ul>
  </body>
</html>

Both the & and the <Effective> in the data are escaped. The link is URL-encoded first, then HTML-escaped by the builder.

Because tags are functions on typed receivers, the compiler rejects invalid nesting. li is only available inside list elements such as ul and ol, and td only inside tr.

Layouts and reusable components

Template engines use "layouts" and "partials" to avoid repetition. With kotlinx.html these are ordinary functions:

import kotlinx.html.*
import kotlinx.html.stream.appendHTML

data class User(val name: String, val email: String, val admin: Boolean)

// a layout: every page gets the same head, nav and footer
fun Appendable.page(pageTitle: String, content: MAIN.() -> Unit) {
    append("<!DOCTYPE html>\n")
    appendHTML().html {
        lang = "en"
        head {
            meta(charset = "utf-8")
            title(pageTitle)
            link(rel = "stylesheet", href = "/style.css")
        }
        body {
            nav { a("/") { +"Home" }; +" | "; a("/users") { +"Users" } }
            main { content() }
            footer { +"(c) 2026 Example" }
        }
    }
}

// a reusable component: an extension on FlowContent works inside any block element
fun FlowContent.userCard(u: User) {
    div(classes = "card") {
        if (u.admin) classes += "admin"
        attributes["data-email"] = u.email
        h3 { +u.name }
        if (u.admin) p("badge") { +"admin" }
    }
}

fun FlowContent.alert(kind: String, block: DIV.() -> Unit) =
    div("alert alert-$kind") { block() }

fun main() {
    val users = listOf(User("Ann", "ann@example.com", true), User("Bob", "bob@example.com", false))
    val out = StringBuilder()
    out.page("Users") {
        h1 { +"Users (${users.size})" }
        alert("info") { +"Showing "; b { +"all" }; +" users." }
        users.forEach { userCard(it) }
        form(action = "/users", method = FormMethod.post) {
            textInput(name = "name") { placeholder = "Name"; required = true }
            submitInput { value = "Add" }
        }
    }
    print(out)
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Users</title>
    <link href="/style.css" rel="stylesheet">
  </head>
  <body>
    <nav><a href="/">Home</a> | <a href="/users">Users</a></nav>
    <main>
      <h1>Users (2)</h1>
      <div class="alert alert-info">Showing <b>all</b> users.</div>
      <div class="card admin" data-email="ann@example.com">
        <h3>Ann</h3>
        <p class="badge">admin</p>
      </div>
      <div class="card" data-email="bob@example.com">
        <h3>Bob</h3>
      </div>
      <form action="/users" method="post"><input type="text" name="name" placeholder="Name" required="required"><input type="submit" value="Add"></form>
    </main>
    <footer>(c) 2026 Example</footer>
  </body>
</html>

Notes:

Since components are plain Kotlin, you can unit-test them, find their usages in the IDE and refactor them safely. Renaming a field in User breaks the build instead of silently printing an empty string.

Fragments, raw HTML and streaming

createHTML() can start from any tag, which is useful for HTMX-style partial responses. prettyPrint = false removes the indentation. unsafe { +"..." } inserts markup without escaping. Use it only for trusted content, such as HTML produced by your own Markdown renderer.

For large pages, write directly to a Writer instead of building a String first:

import kotlinx.html.*
import kotlinx.html.stream.appendHTML
import kotlinx.html.stream.createHTML
import java.io.File

fun main() {
    // a fragment, not a whole document, without indentation
    val row = createHTML(prettyPrint = false).tr {
        td { +"42" }
        td { +"<b>not bold</b>" }
        td { unsafe { +"<b>bold</b>" } }   // trusted markup only
    }
    println(row)

    // stream straight to a file (any Appendable works: Writer, StringBuilder, System.out)
    val f = File.createTempFile("report", ".html")
    f.bufferedWriter().use { w ->
        w.appendHTML().table {
            for (i in 1..3) tr { td { +"row $i" } }
        }
    }
    println(f.readText())
    f.delete()
}
<tr><td>42</td><td>&lt;b&gt;not bold&lt;/b&gt;</td><td><b>bold</b></td></tr>
<table>
  <tr>
    <td>row 1</td>
  </tr>
  <tr>
    <td>row 2</td>
  </tr>
  <tr>
    <td>row 3</td>
  </tr>
</table>

Template engines

A template engine keeps the template in a separate text file, usually under src/main/resources/templates. Templates can be edited without touching Kotlin code and, depending on configuration, reloaded without a restart. The cost is that typos in variable names are found at run time, not at compile time.

All the engines below follow the same pattern:

  1. Create the engine or configuration once at startup. It parses and caches templates and is thread-safe.
  2. Get a template by name.
  3. Render it with a model, either a Map or an object whose getters the engine reads. Kotlin val properties compile to getters, so data classes work as models directly.

Mustache

Mustache is a "logic-less" template language: there are no if statements or expressions, only sections that repeat for lists, render once for truthy values, and are skipped for null, false or empty lists. Implementations exist for almost every language, so the same templates can be shared with a JavaScript frontend. JMustache is a small implementation with no dependencies:

dependencies {
    implementation("com.samskivert:jmustache:1.16")
}
import com.samskivert.mustache.Mustache
import java.io.StringReader

data class Order(val id: Int, val customer: String, val items: List<Line>, val note: String?) {
    val total get() = items.sumOf { it.qty * it.price }
}
data class Line(val name: String, val qty: Int, val price: Int)

// partials are looked up by name; in an app they'd usually be files on the classpath
val partials = mapOf(
    "line" to "<li>{{qty}} x {{name}} @ {{price}}</li>\n",
)

val template = """
<h2>Order #{{id}} for {{customer}}</h2>
<ul>
{{#items}}
  {{> line}}
{{/items}}
{{^items}}
  <li>(empty)</li>
{{/items}}
</ul>
{{#note}}
<p class="note">{{note}}</p>
{{/note}}
<p>Total: {{total}}</p>
""".trimStart()

fun main() {
    val compiler = Mustache.compiler()
        .withLoader { name -> StringReader(partials.getValue(name)) }
        .defaultValue("")          // render missing values as empty instead of throwing
    val tpl = compiler.compile(template)   // compile once, reuse many times

    val order = Order(7, "Ann <ann@example.com>", listOf(Line("Pen", 2, 3), Line("Pad", 1, 5)), null)
    print(tpl.execute(order))
    println("---")
    // a Map works as the context too
    print(tpl.execute(mapOf("id" to 8, "customer" to "Bob", "items" to emptyList<Any>(), "note" to "gift", "total" to 0)))
}
<h2>Order #7 for Ann &lt;ann@example.com&gt;</h2>
<ul>
  <li>2 x Pen @ 3</li>
  <li>1 x Pad @ 5</li>
</ul>
<p>Total: 11</p>
---
<h2>Order #8 for Bob</h2>
<ul>
  <li>(empty)</li>
</ul>
<p class="note">gift</p>
<p>Total: 0</p>

Syntax summary:

The total property is computed in Kotlin. Since Mustache has no expressions, logic like this goes into the model. By default JMustache throws an exception when a variable is missing. defaultValue("") or nullValue("") relaxes that.

FreeMarker

Apache FreeMarker is a mature engine with a rich expression language, macros, number and date formatting, and auto-escaping by output format.

dependencies {
    implementation("org.freemarker:freemarker:2.3.35")
}

src/main/resources/templates/macros.ftlh:

<#macro tag name><span class="tag">${name}</span></#macro>

src/main/resources/templates/products.ftlh:

<#import "macros.ftlh" as m>
<h1>${title}</h1>
<#list products as p>
<div class="product${p?is_first?then(' first', '')}">
  ${p?counter}. ${p.name}: ${p.price?string.currency}<#if p.discount??> (-${p.discount}%)</#if>
  <#list p.tags as t><@m.tag name=t/><#sep> </#list>
</div>
<#else>
<p>No products.</p>
</#list>
<footer>${footer!"no footer"} ${banner?no_esc}</footer>
import freemarker.template.Configuration
import freemarker.template.TemplateExceptionHandler
import java.io.StringWriter
import java.util.Locale

data class Product(val name: String, val price: Double, val tags: List<String>, val discount: Int?)

// create once per application: it caches parsed templates and is thread-safe after setup
val freemarker = Configuration(Configuration.VERSION_2_3_35).apply {
    setClassForTemplateLoading(Product::class.java, "/templates")
    // with this "incompatible improvements" version, *.ftlh files are HTML auto-escaped
    recognizeStandardFileExtensions = true
    defaultEncoding = "UTF-8"
    locale = Locale.US
    templateExceptionHandler = TemplateExceptionHandler.RETHROW_HANDLER
    logTemplateExceptions = false
}

fun main() {
    val model = mapOf(
        "title" to "Tools & <Gadgets>",
        "products" to listOf(
            Product("Hammer", 12.5, listOf("steel", "home"), null),
            Product("Drill", 89.99, listOf("power"), 15),
        ),
        "banner" to "<em>trusted</em>",
    )
    val out = StringWriter()
    freemarker.getTemplate("products.ftlh").process(model, out)
    print(out)
}
<h1>Tools &amp; &lt;Gadgets&gt;</h1>
<div class="product first">
  1. Hammer: $12.50
  <span class="tag">steel</span> <span class="tag">home</span>
</div>
<div class="product">
  2. Drill: $89.99 (-15%)
  <span class="tag">power</span>
</div>
<footer>no footer <em>trusted</em></footer>

Things to know:

Pebble

Pebble uses a Jinja/Twig-like syntax that many web developers already know. Its main strength is template inheritance: a child template extends a base template and overrides named blocks.

dependencies {
    implementation("io.pebbletemplates:pebble:4.1.2")
}

src/main/resources/templates/base.peb:

<!DOCTYPE html>
<html>
<head><title>{% block title %}My site{% endblock %}</title></head>
<body>
{% block content %}{% endblock %}
<footer>Rendered for {{ user.name | default("guest") }}</footer>
</body>
</html>

src/main/resources/templates/orders.peb:

{% extends "base" %}
{% block title %}Orders - {{ parent() }}{% endblock %}
{% block content %}
<h1>{{ orders | length }} orders</h1>
<table>
{% for o in orders %}
  <tr class="{{ loop.index is even ? 'even' : 'odd' }}">
    <td>{{ o.id }}</td><td>{{ o.customer | upper }}</td>
    <td>{{ o.amount | numberformat("#,##0.00") }}</td>
    <td>{{ o.placed | date("yyyy-MM-dd") }}</td>
  </tr>
{% else %}
  <tr><td colspan="4">No orders</td></tr>
{% endfor %}
</table>
{% endblock %}
import io.pebbletemplates.pebble.PebbleEngine
import io.pebbletemplates.pebble.loader.ClasspathLoader
import java.io.StringWriter
import java.time.LocalDate

data class Order(val id: Int, val customer: String, val amount: Double, val placed: LocalDate)
data class User(val name: String)

val pebble: PebbleEngine = PebbleEngine.Builder()
    .loader(ClasspathLoader().apply { prefix = "templates"; suffix = ".peb" })
    .build()   // HTML auto-escaping is on by default

fun main() {
    val orders = listOf(
        Order(1, "ann", 1234.5, LocalDate.of(2026, 10, 1)),
        Order(2, "<bob>", 99.0, LocalDate.of(2026, 10, 3)),
    )
    val ctx = mapOf<String, Any>("orders" to orders, "user" to User("Ann"))

    val out = StringWriter()
    pebble.getTemplate("orders").evaluate(out, ctx)
    print(out)
}
<!DOCTYPE html>
<html>
<head><title>Orders - My site</title></head>
<body>
<h1>2 orders</h1>
<table>
  <tr class="even">
    <td>1</td><td>ANN</td>
    <td>1,234.50</td>
    <td>2026-10-01</td>
  </tr>
  <tr class="odd">
    <td>2</td><td>&lt;BOB&gt;</td>
    <td>99.00</td>
    <td>2026-10-03</td>
  </tr>
</table>
<footer>Rendered for Ann</footer>
</body>
</html>

{{ ... }} prints an expression and {% ... %} is a tag (for, if, block, extends, include, macro). Filters such as upper, default, numberformat and date are applied with |. loop.index starts at 0. {{ parent() }} inside a block renders the base template's content for that block. Auto-escaping is on by default; {{ html | raw }} disables it for one value.

Pebble works with java.time types directly, as LocalDate in the date filter shows.

Thymeleaf and others

Templates in Ktor

Ktor has plugins for kotlinx.html and for most engines (ktor-server-html-builder, ktor-server-freemarker, ktor-server-mustache, ktor-server-pebble, ktor-server-thymeleaf). This example serves one page of each kind and requests both:

dependencies {
    implementation("io.ktor:ktor-server-netty:3.6.0")
    implementation("io.ktor:ktor-server-html-builder:3.6.0")
    implementation("io.ktor:ktor-server-freemarker:3.6.0")
}
import freemarker.cache.ClassTemplateLoader
import freemarker.core.HTMLOutputFormat
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.freemarker.*
import io.ktor.server.html.*
import io.ktor.server.netty.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.html.*

fun Application.module() {
    install(FreeMarker) {
        templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates")
        outputFormat = HTMLOutputFormat.INSTANCE   // auto-escaping
    }
    routing {
        get("/hello") {
            val name = call.request.queryParameters["name"] ?: "world"
            call.respondHtml {
                head { title("Hello") }
                body { h1 { +"Hello, $name!" } }
            }
        }
        get("/products") {
            val model = mapOf("title" to "Products", "products" to emptyList<Any>(), "banner" to "")
            call.respond(FreeMarkerContent("products.ftlh", model))
        }
    }
}

fun main() {
    val server = embeddedServer(Netty, port = 8089, module = Application::module).start(wait = false)
    val http = java.net.http.HttpClient.newHttpClient()
    for (path in listOf("/hello?name=%3Ci%3EAnn", "/products")) {
        val req = java.net.http.HttpRequest.newBuilder(java.net.URI("http://localhost:8089$path")).build()
        val resp = http.send(req, java.net.http.HttpResponse.BodyHandlers.ofString())
        println("${resp.statusCode()} ${resp.headers().firstValue("content-type").get()}")
        println(resp.body())
    }
    server.stop(100, 500)
}
200 text/html; charset=UTF-8
<!DOCTYPE html>
<html>
  <head>
    <title>Hello</title>
  </head>
  <body>
    <h1>Hello, &lt;i&gt;Ann!</h1>
  </body>
</html>

200 text/html; charset=UTF-8
<h1>Products</h1>
<p>No products.</p>
<footer>no footer </footer>

Ktor's FreeMarker plugin creates its own Configuration with an old default compatibility level, so .ftlh files are not auto-escaped unless you set outputFormat = HTMLOutputFormat.INSTANCE. Without that line, the ?no_esc in the template is a syntax error, and plain ${...} would output values unescaped.

For more on serving pages, see HTTP middleware and HTTP headers.

Choosing an approach

Need Use
Short text built in code (log lines, messages, CLI output) String templates, buildString
Text whose wording is stored outside code, no logic {placeholder} substitution
HTML written by Kotlin developers, compile-time safety kotlinx.html
Templates shared with a JavaScript frontend Mustache
Rich formatting, macros, emails and reports FreeMarker
Web pages with layout inheritance Pebble (or FreeMarker, Thymeleaf)

Whatever you choose:

  1. Never build HTML by concatenating strings with unescaped user data.
  2. Create engines once and reuse them. Parsing a template on every request is slow.
  3. Make missing variables fail loudly in development and tests.
  4. Keep logic in Kotlin and keep templates to presentation: compute totals, filtering and permissions in the model.
  5. Render templates in unit tests and check the output, so a renamed property breaks a test rather than a production page.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents