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 and faster page loading times. However, when I just create a JS file in the public folder, all the @{Controller.method} link replacements are no longer working. I was thinking about calling some initialization function from the HTML templates which just supplies the required URLs like
initialize({ "Application.doThis" : "@{Application.doThis}"})
however this is becoming very cumbersome and error-prone with any URL that is added. Another thing is, that the I18N also no longer works. So what is the best practice for scenarios like these, where you have your JS code in a separate file but still want to use URL generation and I18N in your JS?
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:To your
conf/routes
file add: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
: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.In the main template, generate a 'Javascript router', something like:
And then in any 'static' javascript file, use this router: