Play Framework template, which is actually a JS file

I would like to have a play template that is a JS file (as opposed to the <script> tags inside the HTML template). The reason for this is that the script can be cached. However, I need to create differences in the script depending on where it is included and hopes to do this using the playback template system. I can already do this if I use the built-in scripts, but they cannot be cached.

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

+6
source share
1 answer

It's simple, simple ... create a view with the extension .js , i.e.: views/myDynamicScript.scala.js :

 @(message: String) alert('@message'); //Rest of your javascript... 

So you can do it with Scala , like:

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

or using Java :

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

Create a route action for you (you might want to add some parameters to it):

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

So you can include it in HTML templite, like:

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

Not necessary:

You can also display the script in your HTML document, i.e. by placing it in the <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 types of templates

+15
source

Source: https://habr.com/ru/post/977735/


All Articles