Reputation: 141
I am trying to use Spray to fulfill my routing needs for a Scala based web application. I'm wondering how you can pass a Scala val to a front end resource, such as using a variable inside an HTML file. What is the appropriate way to accomplish this? (If this is 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 out {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 am hoping there is a way to separate the views from the routing logic itself and into their own files. Is this doable or will I need to define HTML inside the routes?
Upvotes: 3
Views: 287
Reputation: 1457
You may try to use Twirl for you needs.
A short example that's taken from the github page examples
@(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>
Upvotes: 2