Itchy Itchy - 3 months ago 32
Scala Question

Play Framework 2.4 use injected variable in Scala template

I would like to show some data from the database in the menubar of my web page. To get the data, I have a data-access-object (DAO) which is usually created with Guice injection.

How can I use such an (injected) object in my Scala templates?

I could pass it as a parameter to the template, but I had to do this on every single page (because it should be displayed in the menubar). I'm looking for another solution where I don't have to pass it everywhere. Currently I'm creating a new object inside the template, whenever it is rendered (which gets me a cleaner code but a worse performance).

Answer

You can kinda-sorta fake this without too much effort.

First, create a Scala object that provides access to your DAO (this can contain as many things as you want, just repeat the pattern within the top-level object and the Implicits object).

package com.example.stuff

object ViewAccessPoint {
  private[stuff] val myDaoCache = Application.instanceCache[MyDao]

  object Implicits {
    implicit def myDao(implicit application: Application): MyDao = myDaoCache(application)
  }
}

In your view, you can then import the Implicits object into your template and get hold of the DAO created by Guice.

@import com.example.stuff.ViewAccessPoint.Implicits._
@import play.api.Play.current

myDao.whatever()

This works for both Java and Scala projects.

You can see this in practice here:

On a side note, I would consider if you really want to be doing data access in your template layer.

Comments