注入MessageApi并使用I18nSupport Trait

时间:2015-12-14 01:23:27

标签: scala playframework playframework-2.4

我的控制器操作使用类似于以下内容的自定义操作:

class ActionWithContext @Inject()(....)
  extends ActionBuilder[ContextAwareRequest] {

  def invokeBlock[A](request: Request[A], block: (ContextAwareRequest[A]) =>                   Future[Result]) = {
  ... 
  }

}

class ContextAwareRequest[A](val context: MyContext, request: Request[A]) extends WrappedRequest[A](request)

我的控制器如下:

import play.api.i18n.{MessagesApi, I18nSupport, Messages}
import play.api.i18n.Messages.Implicits._
class WebsiteController @Inject() (val messagesApi: MessagesApi, actionWithContext: ActionWithContext, ..)
      extends BaseController with I18nSupport {


    def edit(websiteId: Int)  =  actionWithContext { request =>
        val model = ..
        Ok(views.html.backend.websites.edit(model)(request.context))
      }

    }

视图页面如下所示:

@(form: Form[controllers.WebsiteForm])(implicit context: MyContext, m: Messages) {


}

我收到错误:

not enough arguments for method apply: (implicit context: com.example.services.components.MyContext, implicit m: play.api.i18n.Messages)play.twirl.api.HtmlFormat.Appendable in class edit.
[error] Unspecified value parameter m.
[error]     Ok(views.html.websites.edit(model)(request.context))
[error]                                

我尝试传递messageApi,如:

 Ok(views.html.websites.edit(model)(request.context, messageApi))

但是我在Messages和MessageApi之间遇到了类型不匹配错误。

我该怎么办?

P.S我甚至没有在我的观点中使用消息,但我正在使用表单助手,我猜这些消息在封面下使用...

1 个答案:

答案 0 :(得分:9)

看起来你正试图明确传递一个隐式参数而另一个隐式传递。你必须明确地传递它们:

Ok(views.html.websites.edit(model)(request.context, implicitly[Messages]))

或两者都含蓄地说:

implicit val context = request.context
Ok(views.html.websites.edit(model))