I have a Play Scala 2.5 application. I would like to know how to return Twirl template (if possible) inside another Twirl template from scala code.
Example : I have several Twirl templates corresponding to html input element. One template for input text, another for input checkbox and so on. I have a main template and inside I call a helper method from a Scala object or class and based on some condition I return the Twirl template for the wanted input element.
In this answer I suppose that your templates have the same input parameters and output type(HTML). Play docs say that templates are compiled to normal Scala functions.
For example, let's say you have two templates, template1 and template2, and they both have input parameter a: String
. The main template should use either of those two, so it has a parameter of template: String => HtmlFormat.Appendable
.
template1:
@(a: String)
@{ a + " world!" }
template2:
@(a: String)
@{ a + " Stackoverflow!" }
main:
@(template: String => HtmlFormat.Appendable)
@template("Hello")
If we pass template1 we get "Hello world!", and if we pass template2 we get "Hello Stackoverflow!".
Now, you could define a method getTemplate
to get the wanted template:
val t1 = views.html.template1.apply _
val t2 = views.html.template2.apply _
def getTemplate(param: Int) = if(param == 1) t1 else t2
and finally the Application
controller method:
def showTemplate(param: Int) = Action {
val template = getTemplate(param)
Ok(views.html.mainTemplate(template))
}
and route, of course:
GET /template/:id controllers.Application.showTemplate(id: Int)