How to do JPA query from view template in play
I'm trying to do a JPA query from a view template but it's not working (I've verified that there are records using phpMyAdmin). I know this should normally be done through the controller and passed in v开发者_开发技巧ia render
, but this is part of building a menu which will appear on every page and I don't want to have to modify every controller to accomplish this.
What I'm currently trying is
<ul>
%{
import models.Building;
List<Building> buildings = Building.findAll();
}%
#{list items: buildings, as: 'building'}
<li><a href="">${building}</a></li>
#{/list}
</ul>
but I'm getting the error The template /app/views/Networks/grid.html does not compile : unexpected token: (
referencing the line which calls findAll()
. What's the right way to do this?
Instead of trying to do this in the page (bad practice) or add it to every Controller you should add it to one parent controller in a method annotated with @Before
. This will get called on each page so you only need to do the code once.
Eg. The parent controller (aka interceptor) would look like:
public class ControllerInterceptor extends Controller {
@Before
public static void intercept() {
RenderArgs.current().put("buildings", Building.findAll());
}
}
Then each controller would add the following annotation:
@With(ControllerInterceptor.class)
public class MyController extends Controller {
...
}
And your page code would then refer to it much as you're already doing:
<ul>
#{list buildings, as: 'building'}
<li>#{a @Buildings.edit(building.code)}${building}#{/a}</li>
#{/list}
</ul>
As for why your original code didn't work, I'm not sure. Possibly something to do with how the Model class is enhanced by Play?
Discovered how to work around it, but I'd still be interested to know what was wrong with the original code. I got it working by just doing
<ul>
#{list items: models.Building.findAll(), as: 'building'}
<li>#{a @Buildings.edit(building.code)}${building}#{/a}</li>
#{/list}
</ul>
精彩评论