Monday 1 December 2014

How to dynamically generate JavaScript based on templates in the Java/Scala Play! Framework version 2.3.6



1. In /app/assets/views, Create a file “scriptjs.scala.html”
2. In/app/conf/routes, add a route as follows

GET    /script.js     controllers.Application.scriptjs()

3. In app/controllers/Application.java,  add the following method:

public static Result scriptjs() {
String params = “Hello World”;
return ok(views.html.scriptjs.render(params)).as("text/javascript utf-8");
}

4. In your newly created scriptjs.scala.html, add the following

@(params: String)

alert(@params);

5. Now, in your HTML file, add the following tag

<script src=http://YOUR_WEBSITE_HERE.com/script.js></script>

6. If your webpage now pops up an alert message saying "Hello World", you're all done!