文件

§使用範本進行相依性注入

Twirl 範本可以透過在範本頂端使用特殊的 @this(args) 語法宣告建構函式,產生為類別而非靜態物件。這表示 Twirl 範本可以直接注入到控制器中,並管理自己的相依性,而非讓控制器不僅要管理自己的相依性,還要管理它必須呈現的範本的相依性。

舉例來說,假設範本相依於控制器未使用的元件 Summarizer

public interface Summarizer {
  /** Provide short form of string if over a certain length */
  String summarize(String item);
}

使用 @this 語法為建構函式建立檔案 app/views/IndexTemplate.scala.html

@this(summarizer: Summarizer)
@(item: String)

@{summarizer.summarize(item)}

最後,透過在建構函式中注入範本,在 Play 中定義控制器

public class MyController extends Controller {
  
  private final views.html.IndexTemplate template;

  @Inject
  public MyController(views.html.IndexTemplate template) {
    this.template = template;
  }

  public Result index() {
    String item = "some extremely long text";
    return ok(template.render(item));
  }

}

一旦範本定義了其相依性,控制器就可以將範本注入到控制器中,但控制器不會看到 Summarizer

如果你在 Play 應用程式外部使用 Twirl,你必須手動新增 @Inject 註解,表示在此處應使用相依性注入

TwirlKeys.constructorAnnotations += "@javax.inject.Inject()"

在 Play 應用程式內,這已包含在預設設定中。

下一步:常見使用案例


在這個文件裡發現錯誤?此頁面的原始碼可以在 這裡 找到。在閱讀 文件指南 後,請隨時提出 pull request。有問題或建議要分享嗎?前往 我們的社群論壇 與社群展開對話。