§使用範本的依賴性注入
Twirl 範本可以透過在範本最上方宣告一個使用特殊 @this(args) 語法的建構函式,產生為一個類別,而非一個靜態物件。這表示 Twirl 範本可以直接注入到控制器中,並管理它們自己的相依性,而非控制器必須管理相依性,不只針對它自己,也針對它必須呈現的範本。
舉例來說,假設一個範本相依於一個元件 Summarizer
,而控制器並未使用該元件
trait Summarizer {
/** Provide short form of string if over a certain length */
def summarize(item: String)
}
使用 @this 語法為建構函式建立一個檔案 app/views/IndexTemplate.scala.html
@this(summarizer: Summarizer)
@(item: String)
@{summarizer.summarize(item)}
最後,在 Play 中定義控制器,並在建構函式中注入範本
public MyController @Inject()(template: views.html.IndexTemplate,
cc: ControllerComponents)
extends AbstractController(cc) {
def index = Action { implicit request =>
val item = "some extremely long text"
Ok(template(item))
}
}
一旦範本定義了它的相依性,控制器就可以將範本注入到控制器中,但控制器看不到 Summarizer
。
如果你在 Play 應用程式外使用 Twirl,你必須手動加入 @Inject
注解,表示相依性注入應在此處使用
TwirlKeys.constructorAnnotations += "@javax.inject.Inject()"
在 Play 應用程式內,這已經包含在預設設定中。
下一頁:常見使用案例
在此文件發現錯誤?此頁面的原始程式碼可以在 此處 找到。在閱讀 文件指南 後,請隨時貢獻一個 pull request。有問題或建議要分享嗎?前往 我們的社群論壇,與社群展開對話。