I am trying to iterate over a complex value inside a template using Scala Play framework 2.
My variable is the following: tests: List[(String,Option[List[String]])]
I iterate on it like this:
@if(!tests.isEmpty) {
<h3>Tests results</h3>
@tests.map(t => {
<h4>@t._1</h4>
@t._2 match {
case None => {
<p>
<span>
[WARNING] Test failed
</span>
</p>
}
case Some(res) {
@res.map(r => {
<p>
<span>
@r
</span>
</p>
})}
}
})}
but I got the following error: expected start of definition on @t._2 match {.
I guessed that the problem comes from the fact that I use a tuple inside a map. But why? Is there any solution?
The problem lies in the way you’re using curly braces and parenthesis with
map. Everything inside the parenthesis will be treated as scala code. You won’t be able to use html and to use the@as you’re expecting it to work. Inside the curly braces you can use the@that way you want.For instance, this won’t compile and will raise the
expected start of definition:On the other hand, this will compile and work the way it’s supposed to:
I had had problems with the way the template parses the scala code. I’m not entirely sure if they parse it the way the scala compiler parses a scala code. I’ve read before that there’re some limitations. And I’ll show you one in a bit. Your solution compiles and works just fine if you switch the curly braces. And you’ll end up with something like that:
This is not the most idiomatic way to do it. I would probably use a map instead of pattern matching there. But use what fits you. The point here is that
@definingthere. Have you noticed it? If you try to match with t._2 directly you’ll get a')' expected but 'case' found.exception. What is odd to me. And I’ve found that before and I’ve googled it a lot to find out that this is a problem in the current engine and that you have to define the value and then match it the way you want to.Cheers!