Ktor 3.0.0-rc-1 Help

JTE

Ktor allows you to use JTE templates as views within your application by installing the Jte plugin.

Add dependencies

To use Jte, you need to include the ktor-server-jte artifact in the build script:

implementation("io.ktor:ktor-server-jte:$ktor_version")
implementation "io.ktor:ktor-server-jte:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-jte-jvm</artifactId> <version>${ktor_version}</version> </dependency>

Install Jte

To install the Jte plugin to the application, pass it to the install function in the specified module. The code snippets below show how to install Jte...

  • ... inside the embeddedServer function call.

  • ... inside the explicitly defined module, which is an extension function of the Application class.

import io.ktor.server.engine.* import io.ktor.server.netty.* import io.ktor.server.application.* import io.ktor.server.jte.* fun main() { embeddedServer(Netty, port = 8080) { install(Jte) // ... }.start(wait = true) }
import io.ktor.server.application.* import io.ktor.server.jte.* // ... fun Application.module() { install(Jte) // ... }

Inside the install block, you can configure how to load JTE templates.

Configure Jte

Configure template loading

To load JTE templates, you need to:

  1. Create a CodeResolver used to resolve template code. For example, you can configure DirectoryCodeResolver to load templates from a given directory or ResourceCodeResolver to load templates from application resources.

  2. Use the templateEngine property to specify a template engine, which uses a created CodeResolver to transfer templates into native Java/Kotlin code.

For instance, the code snippet below enables Ktor to look up JTE templates in the templates directory:

import gg.jte.TemplateEngine import gg.jte.resolve.DirectoryCodeResolver import io.ktor.server.application.* import io.ktor.server.jte.* import java.nio.file.Path fun Application.module() { install(Jte) { val resolver = DirectoryCodeResolver(Path.of("templates")) templateEngine = TemplateEngine.create(resolver, gg.jte.ContentType.Html) } }

Send a template in response

Suppose you have the index.kte template in the templates directory:

@param id: Int @param name: String <html> <body> <h1>Hello, ${name}!</h1> </body> </html>

To use the template for the specified route, pass JteContent to the call.respond method in the following way:

get("/index") { val params = mapOf("id" to 1, "name" to "John") call.respond(JteContent("index.kte", params)) }
Last modified: 02 April 2024