Home > Enterprise >  Ktor | How to connect FreeMaker-Templates with any kind of File?
Ktor | How to connect FreeMaker-Templates with any kind of File?

Time:07-23

Hello everyone,

I just started learing Kotlin and Ktor for Web Development. I started creating a Template and everything worked perfectly but now I want to add style to my Templates. In the Kotlin Docs they add style with HTML but I would like to add style with a CSS-File or add a favicon to my head section. Is that possible?

NK

CodePudding user response:

You can use FreeMarker templates for any kind of text content, just make sure that your server responds with an appropriate content type. Here is an example:

embeddedServer(Netty, port = 8080) {
    install(FreeMarker) {
        templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates")
    }
    routing {
        get("/style.css") {
            call.respond(
                FreeMarkerContent(
                    "style.css",
                    mapOf("mainColor" to "#aabbcc"),
                    contentType = ContentType.Text.CSS
                )
            )
        }

        get("/") {
            call.respond(FreeMarkerContent("index.html", mapOf<Unit, Unit>()))
        }
    }
}.start(wait = true)

templates/style.css

body {
    background-color: ${mainColor}
}

templates/index.html

<html>
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
</body>
</html>
  • Related