简体   繁体   English

用于创建js文件的Scala模板引擎

[英]Scala template engine for creating js files

I want to create js files using a template engine with Scala. 我想使用带有Scala的模板引擎来创建js文件。 Is it possible with the popular templating engines for Scala, namely Play and Scalate? 流行的Scala模板引擎(即Play和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: 只需使用.js ext创建视图,即: app/views/myScript.scala.js和虚拟内容:

@(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: 或Java版本:

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 请注意,Play应该返回有效的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) 响应中的Content-Type:text/javascript; charset=utf-8 ,无论如何,取决于您使用的版本, 可能需要在操作中手动执行此操作(使用浏览器的检查工具来检查响应类型)

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 . 这实际上取决于您要实现的目标,即JavaScript代码的复杂程度,但是,除非它真的非常简单,否则建议使用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. 这样,您基本上将编写一些可编译为JavaScript的Scala代码,并且您应该能够将这些已编译的JavaScript包含在Play应用程序中。

Advantages of writing Scala vs JavaScript should be pretty obvious (type safety, using lots of the existing Scala libraries). 编写Scala与JavaScript的优势应该非常明显(类型安全,使用大量现有的Scala库)。 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. 缺点是Scala-> JavaScript编译会有所延迟,并且缺少Scala.js和Play的无缝集成,就像Play拥有自己的模板引擎一样。 It's up to you to decide if the extra work to make these 2 work together worth it. 由您决定将这2个项目一起使用是否值得进行额外的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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