Render a Play!Framework2 javascript as template?

拜拜、爱过 提交于 2019-11-30 19:36:17

问题


I'd like to return a .js file from a template in Play!Framework 2.

Here's how I did that :

In my views folder, I created a template file :

initials.scala.js

Containinig something like :

{
    'data': @Model.find.findList()
}

And then, in my controller :

public static Result initials() {
    return ok(views.js.initials.render());
}

This is pretty straighforward for me, but I get this error :

error: package views.js does not exist

What I did wrong?

If I rename js to txt (in the filename and the package call in the controller), everything works fine. But if I change it to js, I get an error.


回答1:


You did nothing wrong, Play allows you tu use only .html, .xml or .txt extensions for views, so you need to use one of them.

From technical point of view it doesn't matter which one you'll use, anyway you need to return it from controller as JavaScript, ie with:

public static Result initials() {
    return ok(views.html.initials.render()).as("application/javascript");
}



回答2:


This is possible by placing a route to the particular asset in your routes definition.

ie. GET /assets/javascripts/initials.js controllers..initials()




回答3:


You can have a scala.js file but you don't call it with views.js.initials.render() but instead js.initials.render()

At least with Scala it works with Play 2.2



来源:https://stackoverflow.com/questions/16235446/render-a-playframework2-javascript-as-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!