我使用 ViewModel 方法来解决这个问题。
默认视图模型:
class DefaultPage(
implicit val request: RequestHeader,
implicit val lang: Lang) {
var title: String = null
val styles = mutable.LinkedHashMap.empty[String, Int]
val scripts = mutable.LinkedHashMap.empty[String, Int]
def title(title: String) {
this.title = title
}
def style(style: String)(implicit priority: Int = 500) {
styles.put(style, priority)
}
def script(script: String)(implicit priority: Int = 500) {
scripts.put(script.toString, priority)
}
def translate(message: String, objects: Any*) = Messages(message, objects: _*)
}
然后我有两个模板标签:
样式.scala.html
@(styles: scala.collection.mutable.Map[String, Int])
@for(style <- styles.toList.sortBy(_._2)) {
<link rel="stylesheet" href="@routes.Assets.at(style._1)" />
}
scripts.scala.html
@(scripts: scala.collection.mutable.Map[String, Int])
@for(script <- scripts.toList.sortBy(_._2)) {
<script async="true" src="@routes.Assets.at(script._1)"></script>
}
我的主要模板:
main.scala.html
@(page: util.view.models.DefaultPage)(content: Html)
@import tags.scripts
@import tags.styles
@page.style("css/vendor/normalize.min.css")(1)
@page.style("css/vendor/formalize.min.css")(1)
@page.style("css/sprites.min.css")(1)
@page.style("css/main.min.css")(1)
@page.style("css/quirks.min.css")(1000)
@page.script("js/vendor/jquery-1.9.1.min.js")(1)
@page.script("js/vendor/jquery.formalize.min.js")(1)
@page.script("js/plugins.min.js")(1)
@page.script("js/main.min.js")(1)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@page.title</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width" />
@styles(page.styles)
<script src="@routes.Assets.at("js/vendor/modernizr-2.6.2.min.js")"></script>
</head>
<body class="@page.lang.code @page.lang.language @page.lang.country">
@content
@scripts(page.scripts)
</body>
还有一个子模板:
@(page: util.view.models.ContactUsPage)
@page.title(page.translate("contact.us.title"))
@page.style("css/contact-us.min.css")
@page.script("js/vendor/jquery.expandable-1.1.4.js")
@page.script("js/contact-us.min.js")
@main(page) {
}