首页 > 解决方案 > 如何在 Koreander 模板中取消转义 html(字符串)?

问题描述

我正在使用lukasjapan/koreander库及其 ktor 支持版本,当我从 kor 文件中调用 ViewModel(Res class) topbar 变量时,它会转义 html 字符串。

这就是我调用 ktor 来提供网页的方式:

suspend fun main() = coroutineScope<Unit> {
    System.setProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE")
    embeddedServer(
        Netty,
        port = 80,
        module = Application::module
    ).apply { start(wait = true) }
}

data class Res(val topbar: String)

fun Application.module() {
    install(KoreanderFeature)
    routing {
        get("/") {
            val text = javaClass.getResource("/templates/topbar.kor").readText()
            val resource = Res(Koreander().render(text, Any()))
            call.respondKorRes("/templates/index.kor", resource)
        }
    }
}

这是我的 topbar.kor 文件:这只是为了测试,所以我把它做得很小。

.navbar-custom
    %ul.list-unstyled.topnav-menu.float-right.mb-0
        %li.d-none.d-sm-block
            %form.app-search

这是我的 index.kor 文件:

%html
    %head
    %body
        %p.hello Hello World!
        $topbar / <- problem here, this has escaped html, browser interpret it as text

这是在浏览器上呈现的内容: 浏览器快照 如何在此处取消转义 html,以便浏览器将其解释为有效的 html 并在那里呈现?

标签: stringkotlinescapingrenderinghtml-escape

解决方案


我从 David Eriksson @官方kotlinlang-slack那里得到了答案

我们可以使用:unsafehtml过滤器来有效地绕过 HTML 转义:

%html
    %head
    %body
        %p.hello Hello World!
        :unsafehtml $topbar

推荐阅读