Search code examples
scalaplayframework-2.0twirl

Pass reference to a template class in Play2 framework template engine


I have a field.scala.html that should take a control as input and render it.

Right now I do like this:

@field("shop", "name", true) { (modelName, fieldName, required) =>
  @textInput(modelName, fieldName, required)
}

But I would like to do it like this: @field("shop", "name", true)(textInput)

I see 2 ways it could be done but not sure if it's possible:

  1. Somehow via reflection call the textInput.apply with appropriate parameters.
  2. Make textInput implement some trait and field would require an instance of this particular trait (more type safe)

Maybe there is a better way?


Solution

  • Templates are just functions. If field.scala.html takes a:

    (String, String, Boolean) => Html
    

    And textInput.Scala.html has the following parameter declaration:

    @(modelName: String, fieldName: String, required: Boolean)
    

    Then what you want to do will just work. If not try passing textInput.apply.