Play Framework [2.4.x] how to address public asset

2020-04-06 13:10发布

问题:

This previous question may serve as a baseline for what "submodules" mean for the purpose of the current discussion: Play Framework [2.4.x] Working with Sub Modules

If you understand a Play submodule then given that context how does one enter the routing entry on the submodule to expose assets from a "public" folder?

Whenever I attempt to make a basic entry (as follows) my entire root module fails to compile a single route and yet I get no "usable" error or other indicator as to what might have happened.

GET   /assets/*file  controllers.Assets.at(path="/public", file)

The compiler errors occur even if I comment out the entry in the root project.

As all my sub modules controllers have a prefix I tried that (of course)

GET   /assets/*file  controllers.submodule.Assets.at(path="/public", file)

Alas that doesn't work either but at least I get a useful error telling me the type Assets is not a member of package controllers.submodule

Any suggestions?

PS: Yes I've also tried taking the entry out of the root's routing file in case it was just a name space collision...

回答1:

You have to create an Assets controller in your submodule controllers package:

package controllers.submodule

class Assets extends AssetsBuilder(DefaultHttpErrorHandler)

Then declare a route for this controller in the router file (it should be named submodule.routes) of your submodule:

GET    /submodule/public/*file    controllers.submodule.Assets.versioned(path="/public", file: Asset)

It is better to prefix the route with the name of your submodule to avoid route colision in case you have other submodules name with static route entry.

One more thing: all your static files are hosted in the "lib" folder of your root module:

lib/submodule/css...
lib/submodule/js...

So you have to update your views like that:

<script type="text/javascript" src="@controllers.submodule.routes.Assets.versioned("lib/submodule/js/your-submodule-script.js")"></script>

EDIT: don't forget to add this to your route file (named routes) of your root module

-> / submodule.routes