[platform-play] TwirlCompiler support for dependency injection with templates
- Dominant language
- Java
- Stars
- 47
- Forks
- 41
- PR merge metrics
- No merged PRs in 30d
Description
Twirl templates can be generated as a class rather than a static object by declaring a constructor using a special @this(args) syntax at the top of the template. This means that Twirl templates can be injected into controllers directly and can manage their own dependencies, rather than the controller having to manage dependencies not only for itself, but also for the templates it has to render.
Reference: https://www.playframework.com/documentation/2.6.x/ScalaTemplatesDependencyInjection
### Expected Behavior
Using the examples in reference site:
```scala
trait Summarizer {
/** Provide short form of string if over a certain length */
def summarize(item: String)
}
```
Template:
```scala
@this(summarizer: Summarizer)
@(item: String)
@{summarizer.summarize(item)}
```
Controller:
```scala
class 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))
}
}
```
The generated class should be:
```scala
class IndexTemplate @javax.inject.Inject() /*2.18*/(summarizer: models.Summarizer) extends _root_.play.twirl.api.BaseScalaTemplate[play.twirl.api.HtmlFormat.Appendable,_root_.play.twirl.api.Format[play.twirl.api.HtmlFormat.Appendable]](play.twirl.api.HtmlFormat) with _root_.play.twirl.api.Template1[String,play.twirl.api.HtmlFormat.Appendable] {
/**/
def apply/*3.14*/(item: String):play.twirl.api.HtmlFormat.Appendable = {
_display_ {
{
Seq[Any](format.raw/*3.28*/("""
"""),_display_(/*5.14*/{summarizer.summarize(item)}),format.raw/*5.42*/("""
"""))
}
}
}
def render(item:String): play.twirl.api.HtmlFormat.Appendable = apply(item)
def f:((String) => play.twirl.api.HtmlFormat.Appendable) = (item) => apply(item)
def ref: this.type = this
}
```
So the class generated is annotated with @Inject **`class IndexTemplate @javax.inject.Inject() /*2.18*/(summarizer: models.Summarizer)`**
### Current Behavior
The current version of gradle-plataform-play does not support dependency injection.
### Suggestions
#### Configuration
- build.gradle
```
sourceSets {
main {
twirl{
constructorAnnotations = [ '@javax.inject.Inject()']
}
}
}
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.