Play! Framework: Best practice to use URLs in separate JavaScript files?

☆樱花仙子☆ 提交于 2019-11-30 05:30:30
Guillaume Bort

In the main template, generate a 'Javascript router', something like:

<script>
    var routes = {
        doThis: #{jsAction @Application.doThis(user, ':param1', ':param2') /},
        doThat: #{jsAction @doThat() /}
    } 
</script>

And then in any 'static' javascript file, use this router:

$.get(routes.doThis({param1: x, param2: 'yop'}))

The trick is to get the framework to parse your javascript, or your CSS, or anything else in the static directories. Here's an easy solution.

Add a controllers.StaticParser controller:

package controllers;
import play.mvc.Controller;

public class StaticParser extends Controller {
    public static void parse(String route) {
        render("/" + route);
    }
}

To your conf/routes file add:

GET  /parse/{<.*>route} StaticParser.parse

The regexp in that route is very important, otherwise you can't add pathing to the request. To request a parsed static resource, such as a js script, use:

<script src="/parse/public/javascripts/test.js"
   language="javascript" type="text/javascript" ></script>

Unfortunately, you can't use the #{script 'test.js' /} format, because the script tag looks for the static file. To correct that irksome-ness, here's a shameless hack of the script tag: the #{parsescript 'test.js'/} tag. It should go to /views/tags/parsescript.tag:

{
 *  insert a parsescript tag in the template.
 *  by convention, referred script must be put under /public/javascripts
 *    src     (required)   : script filename, without the leading path "/public/javascripts"
 *    id      (opt.)       : sets script id attribute
 *    charset (opt.)       : sets source encoding - defaults to current response encoding
 *
 *    #{parsescript id:'datepicker' , src:'ui/ui.datepicker.js', charset:'${_response_encoding}' /}
}*
%{
    (_arg ) && (_src = _arg);

    if (!_src) {
        throw new play.exceptions.TagInternalException("src attribute cannot be empty for script tag");
    }
    _src = "/public/javascripts/" + _src
    try {
        _abs = play.mvc.Router.reverseWithCheck(_src, play.Play.getVirtualFile(_src), false);
    } catch (Exception ex) {
        throw new play.exceptions.TagInternalException("File not found: " + _src);
    }
}%
<script type="text/javascript" language="javascript"#{if _id} id="${_id}"#{/if}#{if _charset} charset="${_charset}"#{/if}  src="/parse${_abs}"></script>

It works exactly like the #{script /} tag, but parses the file before returning it: #{parsescript 'test.js' /}

One could equally shamelessly hack the #{stylesheet /} tag, but I think I've taken up enough space already.


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!