Why am I getting "could not find implicit value for parameter messages: play.api.i18n.Messages"

1.8k Views Asked by At

I am getting the above compilcation error on Messages("title")

import play.api.i18n.Messages
import play.api.mvc._
import scala.concurrent.Future 

trait ApplicationController extends Controller {

  def get = Action.async {
    implicit request => Future.successful(Ok(views.html.index(Messages("title"))))
  }
}

object ApplicationController extends ApplicationController

my messages file in the conf folder of the project contains the following

 title = hello

and my template has takes the following in case you are wondering:

@(title: String)

Why am I getting this compilation error?

2

There are 2 best solutions below

1
On BEST ANSWER

You need to inject it in Play 2.5. For example here is how declaration of one of my controllers looks like:

import play.api.i18n.MessagesApi
import javax.inject._

class ApplicationController @Inject()(
                                           val messagesApi:MessagesApi,
                                           val env:Environment[User, CookieAuthenticator],
                                           implicit val webJarAssets:WebJarAssets,
                                           val timeZoneItemService:TimeZoneItemService,
                                           val userService: UserService,
                                           authInfoRepository: AuthInfoRepository,
                                           passwordHasher: PasswordHasher
                                         )

You can read more on this here.

0
On

Like Alexander mentioned above, I needed to use inject in Play 2.5. The working code now look like this:

import play.api.i18n.{Messages, I18nSupport, MessagesApi}
import play.api.mvc._
import scala.concurrent.Future

class ApplicationController @Inject()(val messagesApi:MessagesApi) extends Controller with I18nSupport{

  def get = Action.async {
    implicit request => Future.successful(Ok(views.html.index(Messages("title"))))
  }
}

if you have a test class you can follow the following logic and make sure you import "play.api.i18n.Messages.Implicits._":

import controllers.ApplicationController
import org.scalatestplus.play.{OneServerPerSuite, PlaySpec}
import play.api.i18n.{MessagesApi, Messages}
import play.api.i18n.Messages.Implicits._
import play.api.mvc.Result 
import play.api.test.FakeRequest
import play.api.test.Helpers._
import scala.concurrent.Future

class ApplicationControllerSpec extends PlaySpec with OneServerPerSuite{

  val applicationController = new ApplicationController(app.injector.instanceOf[MessagesApi])

  "ApplicationController" must {

    "load front page successfully" in {
       val result: Future[Result] = applicationController.get().apply(FakeRequest())

       contentAsString(result) must include(Messages("home.title"))
    }
  }
}