HTML DSL中KTOR中使用模板的优势是哪些?

发布于 2025-02-08 05:04:10 字数 1354 浏览 2 评论 0原文

我刚刚开始学习KTOR,我真的很喜欢使用HTML DSL。阅读文档( https://ktor.io.io oio oio oio oi of模板)我已经看到有一个模板引擎。但是,要么有我看不见的东西,要么我找不到使用它的优势。清洁和易于使用标准的Kotlin扩展功能,例如Div,P,...而不是?

我发布了一个示例,说明如何使用函数在教程上编写示例(可以找到模板示例 shere ):

fun Application.configureRouting() {
    configureArticleRouting()
    routing {
        get("/") {
            val name = "Ktor"
            call.respondHtml(HttpStatusCode.OK) {
                mainLayout(title = name){
                    articleContent(Article("Article Title", "My article content"))
                }
            }
        }
    }
}

fun FlowContent.articleContent(article: Article) {
    article {
        h2 {
            +article.title
        }
        p {
            +article.content
        }
    }
}

fun HTML.mainLayout(title: String, content: FlowContent.() -> Unit) {
    head {
        title {
            +title
        }
    }
    body {
        content()
    }
}

data class Article(val title: String, val content: String)

问题是,使用模板的优势是什么?

谢谢,

I've just started learning Ktor, and I really like the use of the HTML DSL. Reading the docs (https://ktor.io/docs/html-dsl.html#templates) I've seen that there is a Templates engine. However, either there is something that I can't see, or I don't find the advantages of using it. Isn't cleaner and easier to use standard Kotlin extension functions, like the Div, P,... instead?

I post an example of how I would write the example on the tutorial using functions (the template example can be found here):

fun Application.configureRouting() {
    configureArticleRouting()
    routing {
        get("/") {
            val name = "Ktor"
            call.respondHtml(HttpStatusCode.OK) {
                mainLayout(title = name){
                    articleContent(Article("Article Title", "My article content"))
                }
            }
        }
    }
}

fun FlowContent.articleContent(article: Article) {
    article {
        h2 {
            +article.title
        }
        p {
            +article.content
        }
    }
}

fun HTML.mainLayout(title: String, content: FlowContent.() -> Unit) {
    head {
        title {
            +title
        }
    }
    body {
        content()
    }
}

data class Article(val title: String, val content: String)

The question is, what is the advantage of using templates?

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

£冰雨忧蓝° 2025-02-15 05:04:10

使用模板的优点是,没有深刻编程技能的设计师可以完成布局

An advantage of using templates is that designers without profound programming skills can do the layout

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文