Scala template engine for creating js files

I want to create js files using a template engine with Scala. Is it possible with the popular templating engines for Scala, namely Play and Scalate? If possible, than what are the pros and cons for using either of them?

Answers


Just create view with .js ext, i.e.: app/views/myScript.scala.js and dummy content:

@(message: String)

alert("@message");

Then add an action into your controller:

def myScript = Action {
  // use views.js... NOT views.html... !
  Ok(views.js.myScript.render("Whoha! I'm dynamic JS in Scala :)"))
}

or in Java version:

public Result myScript(){
    // use views.js... NOT views.html... !
    return ok(views.js.myScript.render("Yey! I'm dynamic JS in Java :)"));
}

Add the route to this action:

GET    /my-script    controllers.Application.myScript()

So you can use this route directly:

<script src="/my-script"></script> 

note, that Play should return valid Content-Type:text/javascript; charset=utf-8 in the response, anyway depending on version you are using it may be required to enforce this manually within your action (use browser's inspection tool to check the response type)


It really depends on what you want to achieve, i.e. how sophisticated your JavaScript code will be, but, unless it's something really small and simple, I'd suggest using the Scala.js. This way you basically will write some Scala code that will compile into JavaScript, and that compiled JavaScript you should be able to include into your Play application.

Advantages of writing Scala vs JavaScript should be pretty obvious (type safety, using lots of the existing Scala libraries). Disadvantage would be some delays for Scala -> JavaScript compilation, and also lack of the same seamless integration of Scala.js and Play, like Play has with its own templating engine. It's up to you to decide if the extra work to make these 2 work together worth it.


Need Your Help

What are the biggest differences between boost.asio and the current networking TS?

c++ c++11 networking boost boost-asio

The C++ committee is currently working on a Networking Technical Specification. I was wondering what were the biggest differences with boost::asio. Moreover, I heard several times that the udp