2015-04-23 37 views
0

我正在使用Play 2框架與Scala。播放框架和JavaScript資產路由器

我想在我的Javascript中使用@routes.Assets.at(...)以獲取我的資產的路徑。但該框架不編譯assets目錄中的內容。

可能嗎?或者有其他選擇?

+0

你有沒有看ScalaJavascriptRouting ? https://www.playframework.com/documentation/2.3.x/ScalaJavascriptRouting – danielnixon

+0

是的,這很有幫助。但我認爲[this](https://groups.google.com/d/msg/play-framework/-BLgG7R68sI/kUn_6sd5VWcJ)更好。 – davidshen84

+0

如果你知道了,可以考慮自己回答這個問題;-) – Peanut

回答

1

我的解決辦法:

# in the controller, Scala code 
def jsRouterGen = Action { 
    Ok(
    Routes.javascriptRouter("jsRouter")(
    routes.javascript.Assets.at // IntelliJ will tell you this is wrong, but it you are right :) 
    ) 
).as("text/javascript") 
} 

# in html template 
# add in <head> 
<script src='@routes.Application.jsRouterGen'></script> 
<!-- other js that needs this router come after --> 

# in your js 
jsRouter.controllers.Assets.at('/use/it/like/in/html/template'); 

注意兩對:

  • jsRouterGen:這個定義JS路由器代碼
  • jsRouter:它是這個路由器的名稱你將用於js代碼

根據需要更改它們,但要確保它們匹配。

0

放在assets目錄下的JavaScript文件沒有編譯,但是查看包含它!所以,你可以聲明全局JS變種包括JS的JS,比用這個變種,像以前一樣:

<script> 
    var myPathToSomeAction = '@routes.MyController.myAction()'; 
    var someImgPath = '@routes.Assets.at("images/some-img.jpg")'; 
</script> 
<script src='@routes.Assets.at("js/myscript.js")'></script> 

所以在你的JS,你可以用它即像:

var imgMarkup = '<img src="' + someImgPath + '" alt="" />'; 
+0

謝謝,但這是解決這類問題的老方法。創建客戶端路由器功能更可靠。 – davidshen84