Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework template that is actually a JS file

I'd like to have a Play template that is a JS file (as opposed to having <script> tags inside an HTML template). The reason for this is so that the script can be cached. However, I need to create a differences in the script depending on where it's included and hoped to do this with Play's template system. I can already do so if I use embedded scripts, but those can't be cached.

I found an existing question that also asks the same thing, but the answer is totally different (different goals).

like image 388
Mike Avatar asked Nov 05 '14 00:11

Mike


Video Answer


1 Answers

That's easy, just... create view with .js extension, i.e.: views/myDynamicScript.scala.js:

@(message: String)

alert('@message');

//Rest of your javascript...

So you can render it with Scala action as:

def myDynamicScript = Action {
  Ok(views.js.myDynamicScript.render(Hello Scala!")).as("text/javascript utf-8")
}

or with Java action:

public static Result myDynamicScript() {
    return ok(views.js.myDynamicScript.render("Hello Java!"));
}

Create the route to you action (probably you'll want to add some params to it):

GET   /my-dynamic-script.js      controllers.Application.myDynamicScript()

So you can include it in HTML templite, just like:

<script type='text/javascript' src='@routes.Application.myDynamicScript()'></script>

Optionally:

You can also render the script into your HTML doc, ie by placing this in your <head>...</head> section:

<script type='text/javascript'>
    @Html(views.js.myDynamicScript.render("Find me in the head section of HTML doc!").toString())
</script>

Edit: @See also samples for other templates types

like image 117
biesior Avatar answered Sep 19 '22 09:09

biesior