Play Framework - Set URL for Assets

2019-06-14 08:51发布

问题:

In production, I want to use nginx for serving statics. How to set a URL for assets in Play framework that we can use in both development and production. I like the way Django set STATIC_URL in settings.

EDIT:

In Django, you can set STATIC_URL = 'https://static.domain.com/' in settings.py. In templates, you can call the value for:

<script src='{{ STATIC_URL }}js/jquery.js'></script>

回答1:

You can add anything you need to the application.conf, so for an instance it can be the static domain (other than current app's domain), next you can ie. write simple getter in your controller (Java version):

application.conf

staticUrl = "https://static.domain.com/"

controller Application.java

public class Application extends Controller {
    public static final String STATIC_URL = Play.application().configuration().getString("staticUrl", "http://localhost:9000");
    public static String getStaticUrl(String path){
        return STATIC_URL + path;
    }

    //other stuff
}

view:

<script src='@Application.getStaticUrl("js/your_script.js")'></script>
<!-- or just -->
<script src='@(Application.STATIC_URL)js/your_script.js'></script>

By the way...

If you just need to use absolute url pointing to the current domain, you can do it directly in the view using Assets.at function with absoluteURL() ie:

<script src='@routes.Assets.at("js/your_script.js").absoluteURL()'></script> 
<!-- or for https version -->
<script src='@routes.Assets.at("js/your_script.js").absoluteURL(true)'></script>