Chung Do Chung Do - 3 months ago 16
Scala Question

Static assets in play java

I have save path in database, when I use it in view

@for(photo <- photos){
<img src="@routes.Assets.versioned("images/photo.getPath()")" class="img-rounded" alt="Cinque Terre" width="304" height="236">
}


photo.getPath() is not working, I try with @photo.getPath() still not working. Any suggest for me. I use play-java version 2.5. Thank a lot.

Answer

Personally, I find the Twirl syntax a bit unintuitive. The @ marks the start of a scala statement. The length of this statement is determined automatically.

Now looking at the img tag:

<img src="@routes.Assets.versioned("images/photo.getPath()")" class="img-rounded" alt="Cinque Terre" width="304" height="236">

the following piece of code should be identified as a single statement:

routes.Assets.versioned("images/photo.getPath()")

From a scala point of view, the "images/photo.getPath()" is just a String. It will not execute any method on the photo object. I think (I didn't test this) that your issue should be solveable by replacing this part by s"images/${photo.getPath()}". Note that the string interpolation will make sure that the method on the photo object will be called.

This would make your example look like:

@for(photo <- photos) {
    <img src="@routes.Assets.versioned(s"images/${photo.getPath()}")" class="img-rounded" alt="Cinque Terre" width="304" height="236">
}