带有可选参数的路线-Play 2.1 Scala [英] Routes with optional parameter - Play 2.1 Scala

查看:72
本文介绍了带有可选参数的路线-Play 2.1 Scala的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在Play 2.0中,我有这个:

So in Play 2.0 I had this:

GET     /tasks/add              controllers.Tasks.addTask(parentId: Option[Long] = None)
GET     /tasks/:parentId/add    controllers.Tasks.addTask(parentId: Option[Long])

使用这样的控制器方法:

With a controller method like this:

def addTask(parentId: Option[Long]) = Action { 
    Ok(views.html.addTask(taskForm, parentId))  
}

它正在工作.当我迁移到2.1时,似乎在抱怨这些行:No URL path binder found for type Option[Long]. Try to implement an implicit PathBindable for this type.基本上,我要完成的工作是将路由tasks/add和路由tasks/123/add链接到接受Optional[Long]的相同方法.任何想法如何做到这一点?谢谢.

And it was working. As I migrated to 2.1, it seems to complain about these lines with: No URL path binder found for type Option[Long]. Try to implement an implicit PathBindable for this type. Basically, what I am trying to accomplish is to have route tasks/add and route tasks/123/add link to the same method that accepts an Optional[Long]. Any idea how to do this? Thanks.

好吧,所以我得到的不是错误,而是Lighthouse的功能响应:我们删除了路径可绑定对象中的Option [Long]支持,因为没有可选的path参数.您可以实现您自己的可绑定路径,如果需要,它可以支持它."到目前为止,我有2个解决方案,将-1作为parentId传递,我不太喜欢.或使用2种不同的方法,在这种情况下可能更有意义.目前,实现PathBindable似乎不太可行,因此我可能会坚持使用2种方法.

Ok, so I got a kind of it's not a bug, it's a feature response on Lighthouse: "We removed Option[Long] support in path bindables since it doesn't make sense to have a optional path parameter. You can implement your own path bindable that supports it if you please." So far I have 2 solutions, passing -1 as parentId, which I do not really like. Or having 2 different methods, which probably makes more sense in this case. Implementing the PathBindable doesn't seem too feasible right now, so I will probably stick with having 2 methods.

推荐答案

路径参数中支持播放2.0的Option,播放2.1不再支持此功能,因此删除了Option的PathBindable.

Play 2.0 supported Option in path parameters, Play 2.1 no longer supports this, they removed the PathBindable for Option.

一种可能的解决方案是:

One possible solution would be:

package extensions
import play.api.mvc._
object Binders {
  implicit def OptionBindable[T : PathBindable] = new PathBindable[Option[T]] {
    def bind(key: String, value: String): Either[String, Option[T]] =
      implicitly[PathBindable[T]].
        bind(key, value).
        fold(
          left => Left(left),
          right => Right(Some(right))
        )

    def unbind(key: String, value: Option[T]): String = value map (_.toString) getOrElse ""
  }
}

,然后使用routesImport += "extensions.Binders._"将其添加到Build.scala.运行play clean ~run,它应该可以工作.快速重新加载Binders有时只能工作.

And add this to Build.scala using routesImport += "extensions.Binders._". Run play clean ~run and it should work. Reloading the Binders on the fly only sometimes works.

这篇关于带有可选参数的路线-Play 2.1 Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆