Montag, 30. September 2013

Iterating in Scala Play templates and Reverse Routing

Today I finally solved a puzzle that bugged me for the last few days and even though it is in some kind a case of RTFM I decided to put it here because someone else might encounter the same problem

Play has pretty powerful templating engine that allows you to do lots of different stuff when generating html. Two of those features are iterating over lists and genrating URLs by reverse routing.

My problem was that in my template I was not able to get a URL out of the reverse routing and at first I thought there was a mistake in the routes configuration or in the template syntax and searching the web and documentation for it drove me almost mad.

The solution was something completely different though. In a template you can basically inject any Scala code fragment which also includes flow and control structures. The documentation about ScalaTemplating states that you can use a for loop to iterate over list items but the framework also allows you to use the map function of a list to process it's items. The code compiles, the page gets rendered without warnings or errors and everything looks fine at first. But if you want to insert a link generated by reverse routing for each item you are screwed with this approach. For some reason the reverse route does not get generated in this case. -> {
     <a href="@routes.Application.index"></a>   <-- Creates <a href="@routes.Application.index"></a>

@for(item <-items) {
      <a href="@routes.Application.index"></a>   <-- Creates <a href="/"></a>

So to sum it up: Always use "@for" to iterate in Play templates to avoid stuff like this. Though I don't really get why it has to be that way...

Keine Kommentare:

Kommentar veröffentlichen