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

后端 未结 2 418
栀梦
栀梦 2020-12-29 14:39

I am currently reorganizing a Play! project where there is a lot of JS code in the HTML template files. This code should be moved to external JS files for better readability

2条回答
  •  难免孤独
    2020-12-29 15:23

    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:

    
    

    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);
        }
    }%
    
    

    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.


提交回复
热议问题