Could not find implicit value for parameter flash

2019-04-19 04:27发布

I'm trying to port some code from Play Framework Java to Play Framework Scala but I'm having some issues with porting a tag.

The tag in question in the Java version checks the contents of the Flash scope and creates notifications to the user according to its values (error, success, etc).

I tried to create a Scala view (flag.scala.html):

@()(implicit flash:play.mvc.Scope.Flash)

@if(flash.get("error")) {
    <p style="color:#c00">
        @flash.get("error")
    </p>
}

Which I call from main.scala.html via:

@views.Application.html.flag()

The error I get is:

The file {module:.}/tmp/generated/views.html.main.scala could not be compiled. Error raised is : could not find implicit value for parameter flash: play.mvc.Scope.Flash

The call to the new tag is correct, as if I replace the content by some String that's shown in the browser.

I'm sure it's something stupid but I got stuck. Any suggestion?

4条回答
贪生不怕死
2楼-- · 2019-04-19 04:29

You should not create an implementation for "implicit flash : Flash" on your own. Just add a "implicit request" to your action and it should work.

More details is here at the end of the page: https://github.com/playframework/Play20/wiki/ScalaSessionFlash

查看更多
Melony?
3楼-- · 2019-04-19 04:39

Ivan had the right suggestion, adding "implicit request". However, his link seems outdated. If you want a more explicit explanation, check out my answer to a similar question, here:

How to pass flash data from controller to view with Play! framework

查看更多
祖国的老花朵
4楼-- · 2019-04-19 04:44

I had the same issue but looking at the documentation i found the following:

If the error ‘could not find implicit value for parameter flash: play.api.mvc.Flash’ is raised then this is because your Action didn’t import a request object. Add an “implicit request=>”

of course the implicit Flash must appear in every view if you have nested views like:

@(implicit flash: Flash){

@main(){<h1>hello</h1>}

}

this view does not use flash scope but if main uses it, should be declared in views using main because the compiler will complain.

source: http://www.playframework.com/documentation/2.1.1/ScalaSessionFlash

查看更多
疯言疯语
5楼-- · 2019-04-19 04:52

I don't know the details of Play, but this compile error is saying you should either:

  1. Pass an explicit instance of play.mvc.Scope.Flash in the call to flag(),

    views.Application.html.flag()(myFlash)
    

    or

  2. Make an implicit instance of Flash available in the scope where flag() is called. You could do this by importing the contents of some object (import some.path.FlashImplicits._) or by defining the implicit instance yourself,

    implicit val myFlash: play.mvc.Scope.Flash = ...
    ...
    views.Application.html.flag()
    

So the real question becomes: where do you want to get this Flash instance from?

查看更多
登录 后发表回答