gpt4 book ai didi

scala - Spray 将 Scala 值传递给资源

转载 作者:行者123 更新时间:2023-12-02 01:45:16 25 4
gpt4 key购买 nike

我正在尝试使用 Spray 来满足我对基于 Scala 的 Web 应用程序的路由需求。我想知道如何将 Scala val 传递给前端资源,例如在 HTML 文件中使用变量。完成此任务的适当方法是什么? (如果可能的话)

我当前的路线代码:

val indexRoute =
get {
path("") {
val name = "hello"
getFromResource("views/index.html")
}
}

我的 html:

<!DOCTYPE html>
<html lang="en">
<body>
<h1>{name}</h1>
</body>
</html>

这显然只是在页面上打印出 {name}

我知道我可以做类似的事情:

val indexRoute = {
get {
path("") {
val name = "hello"
complete {
<html>
<body>
<h1>{name}</h1>
</body>
</html>
}
}
}
}

但我希望有一种方法可以将 View 与路由逻辑本身分开,并放入它们自己的文件中。这是可行的还是我需要在路由中定义 HTML?

最佳答案

您可以尝试使用 Twirl为你的需要。

取自 github 页面示例的简短示例

@(name: String, age: Int = 42)
<html>
@* This template is a simple html template --- (this text btw. is a comment and is not rendered) *@
<h1>Welcome @name!!</h1>
<p>You are @age years old, @(if(age < 21) <i>shouldn't you be in bed ?!</i> else <i>have a great evening !</i>)</p>
</html>

关于scala - Spray 将 Scala 值传递给资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26051279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com