Play 2.0 templating - Scala `match` and` val` do not compile in the view template

I have the following code in a Play 2.0 template:

@content.toString.lines.map{ case line => // i put `case` here as another attempt to make it work line match { case "" => @Html("") case _ => <li>@Html(line)</li> /*CRASH*/ } } 

It does not work on the marked line, saying that not found: value line . The second option:

 @for(line <- content.toString.lines){ @line match { /*CRASH*/ case "" => @Html("") case _ => <li>@Html(line)</li> } } 

doesn't work on the marked line, claiming that 'case' expected but identifier found .

UPDATE:

The same goes for val :

 @val headID = "head" 

illegal start of simple expression appears.

UPDATE ENDS

I would like to know what I am doing wrong and how to correctly implement the match-case and val structure in play patterns?

+6
source share
4 answers

Using match expressions in templates

You need to enclose the HTML content of your templates in braces ("{" and "}"):

 @for(line <- content.toString.lines) { @line match { case "" => { } case _ => { <li>@Html(line)</li> } } } 

In your particular case, the following code would be better to read IMHO:

 @content.toString.lines.collect { case line if !line.isEmpty => { <li>@Html(line)</li> } } 

Definition of Values

You can determine the values ​​using the defining[T](value: T)(usage: T => Html) :

 @defining(1 + 2 * 3) { value => <div>@value</div> } 
+22
source

I found that adding {} out to include all the code would work

 @{content.toString.lines.map{ line => line match { case "" => @Html("") case _ => <li>@Html(line)</li> }} 
+4
source

seems to work for me

 @content.toString.lines.map{ line => line match { case "" => @Html("") case _ => <li>@Html(line)</li> } 

by sight, but you can look target/scala-2.9.1/src_managed/main/views/html/index.template.scala in the directory of the playback project to see how to put it in string literals.

As for val assignment, I don't know, but @define can help

+1
source

Another common reason for this error is that the initial bracket is on a separate line:

 @x match { case y => { //offending brace, put it back on the same line as case } //This can go anywhere } 
0
source

Source: https://habr.com/ru/post/912661/


All Articles