简体   繁体   中英

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?

Just create view with .js ext, ie: 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 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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM