Automatically inject WebJarAssets in Play 2.5 HTML template?

强颜欢笑 提交于 2019-12-04 06:59:04

Before webjars-play 2.5.0 there was a static method that you could use in your templates. Since Play has been moving away from global state / static methods, that was removed from webjars-play and now you need to inject WebJarAssets. Unfortunately the Twirl templates don't support injection yet. So you have to inject it into your controller and then pass it to your template. Here is a full sample app that does this: https://github.com/webjars/webjars-play/tree/master/test-project

It can write like that.

controller:

class Application @Inject()(implicit webJarAssets: WebJarAssets,
                          val messagesApi: MessagesApi, materializer: Materializer)
  extends Controller with I18nSupport {

template:

@(title: String)(content: Html)(implicit messages: Messages, webJarAssets: WebJarAssets)
<script type='text/javascript' src='@routes.WebJarAssets.at(webJarAssets.locate("jquery.min.js"))'></script>

As @james-ward said in play-2.5.12 with twirl-1.2.0 you can declare inject dependencies in templates but they will become classes and not objects that complicates the reference to the templates from other ones.

The changes are:

project/plugins.sbt

addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.2.0")

main.scala.html

@this(webJarAssets: WebJarAssets)

@(title: String)(content: Html)(implicit messages:Messages)
<script type="text/javascript" 
  src="@controllers.core.routes.WebJarAssets.at(webJarAssets.locate("jquery.min.js"))">
</script>

Note that a caller of the main template should also declare a constructor mainClient.scala.html:

@this(mainRef: main)
@(...)

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