Unable to render a for loop in Twirl

408 Views Asked by At

In a twirl template I'm trying to render a loop of strings and the current code is giving me code errors. I'm sure it's a small detail that I'm missing...

This is my template...

@(title: String)(content: Html)
<!DOCTYPE html>
<html lang="en">
    <head>
        @* Here's where we render the page title `String`. *@
        <title>@title</title>

    </head>
    <body>
        @content
</script>
    </body>
</html>

And this is where I use this template and try to do a for loop...

@(names: ("George", "John", "Ally"))

@list("List of names")  {
  <h1>Test</h1>
  <ul>
    @for(name <- names) {
      <li>@name</li>
    }
  </ul>
}

And my controller...

package controllers;

import play.mvc.*;

public class NewController extends Controller {
    public Result newPage() {
        return ok(views.html.newPage.render());
    }

}

Here is the error....

Compilation error
':' expected but identifier found.

In G:\Github\playExample - Copy\example\app\views\newPage.scala.html:10
6    @for(name <- names) {
7      <li>@name</li>
8    }
9  </ul>
10} 

What am I missing?

1

There are 1 best solutions below

0
pedrorijo91 On

Your question is still very confusing.

I'm going to recommend you to see this project again https://github.com/pedrorijo91/play-slick3-steps (or any simple play project).

You tag this as Scala, but your controller is clearly a java controller.

In the controller your should have something like:

class Controller @Inject()(val controllerComponents: ControllerComponents) extends BaseController {

  def newPage() = Action { implicit request: Request[AnyContent] =>
    Ok(views.html.newPage())
  }

Then in the view, you seem to have the first template ok, but I don't understand the second part you added. Is it a partial? what's the file name? where/how is it being called?

I would expect something like this:

@(names: List[String])

<h1>Test</h1>
<ul>
    @for(name <- names) {
        <li>@name</li>
    }
</ul>

I don't understand the syntax you are using