本文介绍了生成Play 2的JavaScript路由器的详细方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我以相当冗长的方式定义了我应用的javascript路由器

Currently I define my app's javascript router in a fairly verbose way

def javascriptRoutes = Action { implicit request =>
  import routes.javascript._
  Ok(Routes.javascriptRouter("jsRoutes")(
    Login.method1,Login.Method2,
    OtherController.method1,OtherController.method2,
    //[...]
  )).as("text/javascript")
}

我真正想做的是用routes文件中的所有路由创建一个javascriptRouter,因此我不必在每次添加新控制器时手动更新javascriptRoutes定义.方法.

What I really would like to do is to create a javascriptRouter with all of the routes in the routes file, so I don't have to manually update the javascriptRoutes definition each time I add a new controller method.

有没有一种方法可以完成此任务,或者有没有那么冗长的定义javascriptRouter的方法?

Is there a way to accomplish this task, or is there even a slightly less verbose way of defining the javascriptRouter?

推荐答案

您可以像这样通过反射来做到这一点:

You can do it via reflection like so:

val routeCache = {
    import routes._
    val jsRoutesClass = classOf[routes.javascript]
    val controllers = jsRoutesClass.getFields().map(_.get(null))
    controllers.flatMap { controller =>
        controller.getClass().getDeclaredMethods().map { action =>
            action.invoke(controller).asInstanceOf[play.core.Router.JavascriptReverseRoute]
        }
    }
}

def javascriptRoutes = Action { implicit request =>
    Ok(Routes.javascriptRouter("jsRoutes")(routeCache:_*)).as("text/javascript")
}

这是从target/scala-2.x.x/src_managed中找到的生成的源文件派生的.实际上,您可以添加自己的源生成器并自己解析路由文件,但我发现通过反射进行操作更容易.

This was derived from the generated source files found in target/scala-2.x.x/src_managed. You could actually add your own source generator and parse the routes file yourself, but I find doing it via reflection easier.

您可能想要做的另一件事是过滤掉不需要的方法,因为这将为您提供所有路由(包括javascriptRouter本身).

An additional thing you might want to do is filter out the methods you don't want as this will give you ALL the routes (including the javascriptRouter itself).

这篇关于生成Play 2的JavaScript路由器的详细方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 14:03