Using Freemarker Templates

预计阅读时间:1分钟

Ktor通过FreeMarker功能包括对FreeMarker模板的支持. 使用TemplateLoader初始化FreeMarker功能:

    install(FreeMarker) {
        templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates")
    }

此TemplateLoader设置FreeMarker以在"模板"包中相对于当前类路径的类路径上查找模板文件. 基本模板如下所示:

此功能定义在类io.ktor.freemarker.FreeMarker在神器io.ktor:ktor-freemarker:$ktor_version .
dependencies { implementation "io.ktor:ktor-freemarker:$ktor_version" }
dependencies { implementation("io.ktor:ktor-freemarker:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-freemarker</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>
<html>
<h2>Hello ${user.name}!</h2>

Your email address is ${user.email}
</html>

使用resources/templates ,可以使用call.respond()方法在应用程序的其他位置访问该模板:

    get("/{...}") {
        val user = User("user name", "user@example.com")
        call.respond(FreeMarkerContent("index.ftl", mapOf("user" to user), "e"))
    }

by  ICOPY.SITE