Running db query in play template

I am feeling to keep some portions(form’s select html) of play template separate so that I can call them in main template based on condition. But in those portions I need data which will be fetched from db. I don’t want to pass data form main template’s controller.
So I need to keep independent database query in those template portions.
Is there any way of doing this?

What comes to my mind is:
In Twirl (Play’s template engine) you can inject components like you can in regular Java classes:
So I guess you can just inject the database and use it in the template:

@this(db: play.db.Database)
@(...template parameters...)
Now inside this template you can use the database:

Hope that helps!

Unfortunately suffering from Error
the template file is

@this(db: services.dbServices.TeacherDAO)

. . . .

when I call this on other template like this
Error generates –

not found: value fromSelectTag

You now also need to inject the fromSelectTag into the template in which you use it:

@this(fromSelectTag: views.html.fromSelectTag)
Now you can use it: @fromSelectTag()

This also means if you want to use that template in a controller you also have to inject that template into the controller as well now:

public class HomeController extends Controller {

    private MyView myView;

    public HomeController(MyView myView) {
        this.myView = myView;

    public Result index() {
        return ok(this.myView.render());


(I did not test this code, but I hope you get the idea)

Thanks a lot, this works!!

1 Like