Spray Pass Scala value to resource
I am trying to use Spray to meet my routing needs for a Scala based web application. I'm wondering how you can pass Scala val for an external resource, for example using a variable inside an HTML file. How can this be done? (If possible)
My current route code:
val indexRoute =
get {
path("") {
val name = "hello"
getFromResource("views/index.html")
}
}
My html:
<!DOCTYPE html>
<html lang="en">
<body>
<h1>{name}</h1>
</body>
</html>
This obviously just ends up printing {name} on the page
I know I can do something like:
val indexRoute = {
get {
path("") {
val name = "hello"
complete {
<html>
<body>
<h1>{name}</h1>
</body>
</html>
}
}
}
}
But I hope there is a way to separate the views from the routing logic itself and into your own files. Is this doable or do I need to define HTML inside the routes?
+3
source to share
1 answer
You can try to use Twirl for your needs.
A short example taken from the sample github pages
@(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>
+2
source to share