Using a map function on a collection in a Play Framework template

Here’s a quick example of how to use a map function call on a Scala collection in a Play Framework template:

@(stocks: List[Stock])

@main("Stocks") {
  
  <h1>Dude, you have @stocks.size Stock(s)</h1>
  
  <ul>
    @stocks.map { stock =>
      <li>@stock.symbol</li>
    }
  </ul>

}

This source code from a Play template file named list.scala.html which I have in a Play $PROJECT/views/stock folder (so the full path within the project is /views/stock/list.scala.html.) I deleted a lot of code from the actual template, but that should be all you need to see to make a map function call on a collection object (List, Array, Vector, etc). The part I find confusing here is when to use the @ symbol, and when not to use it (though as I think about it, maybe the only times I don't the @ symbol are when I define code inside a Play template function).

FWIW, I actually link to an "edit" method when emitting the Stock symbol (which is something like "AAPL" or "GOOG"), like this:

<a href="@routes.Stocks.edit(stock.id)">@stock.symbol</a>

That links to an edit function in a Stocks class (defined as "object Stocks extends Controller"). I'll discuss this more in a future Play Framework tutorial.

Until then, if you want to call a map function on a Scala collection in a Play Framework template, I hope this has been helpful.

This website is a little one-man operation. If you found this information helpful, I’d appreciate it if you would share it.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.