Skip to content

Commit

Permalink
Add support for empty (null) model in FreeMarker templates.
Browse files Browse the repository at this point in the history
Fixes #291
  • Loading branch information
orangy committed Feb 7, 2018
1 parent 66ddfe5 commit 009a0b0
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import io.ktor.util.*
import kotlinx.coroutines.experimental.io.*

class FreeMarkerContent(val template: String,
val model: Any,
val model: Any?,
val etag: String? = null,
val contentType: ContentType = ContentType.Text.Html.withCharset(Charsets.UTF_8))

Expand All @@ -36,7 +36,7 @@ class FreeMarker(val config: Configuration) {
}

private class FreeMarkerOutgoingContent(val template: Template,
val model: Any,
val model: Any?,
etag: String?,
override val contentType: ContentType) : OutgoingContent.WriteChannelContent() {
override suspend fun writeTo(channel: ByteWriteChannel) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ import io.ktor.application.*
import io.ktor.http.*
import io.ktor.response.*

suspend fun ApplicationCall.respondTemplate(template: String, model: Any = emptyMap<String, Any>(), etag: String? = null, contentType: ContentType = ContentType.Text.Html.withCharset(Charsets.UTF_8))
suspend fun ApplicationCall.respondTemplate(template: String, model: Any? = null, etag: String? = null, contentType: ContentType = ContentType.Text.Html.withCharset(Charsets.UTF_8))
= respond(FreeMarkerContent(template, model, etag, contentType))
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,29 @@ class FreeMarkerTest {
}
}

@Test
fun testEmptyModel() {
withTestApplication {
application.setUpTestTemplates()
application.routing {
get("/") {
call.respondTemplate("empty.ftl")
}
}

handleRequest(HttpMethod.Get, "/").response.let { response ->
assertNotNull(response.content)
@Suppress("DEPRECATION")
assert(response.content!!.lines()) {
shouldBe(listOf("<p>Hello, Anonymous</p>", "<h1>Hi!</h1>"))
}
val contentTypeText = assertNotNull(response.headers[HttpHeaders.ContentType])
assertEquals(ContentType.Text.Html.withCharset(Charsets.UTF_8), ContentType.parse(contentTypeText))
assertNull(response.headers[HttpHeaders.ETag])
}
}
}

@Test
fun testCompression() {
withTestApplication {
Expand All @@ -50,7 +73,7 @@ class FreeMarkerTest {
val model = mapOf("id" to 1, "title" to "Hello, World!")

get("/") {
call.respond(FreeMarkerContent("test.ftl", model, "e"))
call.respondTemplate("test.ftl", model, "e")
}
}

Expand Down Expand Up @@ -132,6 +155,10 @@ class FreeMarkerTest {
<p>Hello, $bax{id}</p>
<h1>$bax{title}</h1>
""".trimIndent())
putTemplate("empty.ftl", """
<p>Hello, Anonymous</p>
<h1>Hi!</h1>
""".trimIndent())
}
}
}
Expand Down

0 comments on commit 009a0b0

Please sign in to comment.