Question

I'm using jsRoutes in my Play 2.1.x app. Part of my routes file looks the following way:

GET    /assets/template/js/routes/admin.js           controllers.Admin.jsRoutes
GET    /assets/template/js/routes/salonManagement.js controllers.SalonManagement.jsRoutes

And I would like to use both references in my scala template (that is by design, one controller contains necessary api functions, the other one necessary form submission urls). So in my scala template I have the following part:

<script type="text/javascript" src="@routes.Admin.jsRoutes()"></script>
<script type="text/javascript" src="@routes.SalonManagement.jsRoutes()"></script>

Unfortunately, each generated javascript file starts with var jsRoutes = {};. Therefore, @routes.SalonManagement.jsRoutes() overrides properties of @routes.Admin.jsRoutes() and I can use only the last jsRoutes object.

Now, I know only one workaround. After each jsRoutes declaration I can insert a script that copies old jsRoutes object to a temporary object and then extends new jsRoutes with itself. But that doesn't look like the right way to go.

Isn't there any better way?

Was it helpful?

Solution

There's nothing special about the "jsRoutes" name. You can keep the same method name for consistency among the various controllers, but just pass a different name to the Routes.javascriptRouter method.

OTHER TIPS

Put this in your template. I put it in a main template that wraps the other pages.

<script src="@controllers.routes.Application.jsRoutes()" type="text/javascript"></script> 

and put this in your routes file

#jsroutes for ajax calls
GET     /assets/js/routes           controllers.Application.jsRoutes()

And then in your Application controller, refer to whatever method in whatever controller you want by implementing this method

public Result jsRoutes()
{
    response().setContentType("text/javascript");
    return ok(Routes.javascriptRouter("jsRoutes", 
              routes.javascript.Signup.forgotPassword(),
              routes.javascript.Customers.findByName(),
              routes.javascript.Customers.findByNumber()
              ));
}

These correspond with routes like

GET     /customerfind/:name            controllers.Customers.findByName(name: String)

Note there is no need to include parameters for the calls configured in the jsroutes method. Keeping all of this in one place, the Application controller, seems reasonable as long as it refers to methods implemented in their appropriate controller. Like in this example, a find on customer is in the Customers controller. Also, is kindof nice just having to check the one controller (Application) to see all the methods available through javascript routes for ajax calls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top