Less Verbose way of generating Play 2's javascript router

前端 未结 5 871
北海茫月
北海茫月 2021-02-06 00:54

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

def javascriptRoutes = Action { implicit request =>
  import routes.javascript._
  Ok(R         


        
5条回答
  •  太阳男子
    2021-02-06 00:58

    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")
    }
    

    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.

    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).

提交回复
热议问题