Reputation: 4435
I would like to define some templates in play 2 which takes an other template as a parameter:
@aTemplate(otherTemplate())
I think that should be possible in scala, right?
How would look like the parameter definition in the otherTemplate()
? I should also have a default value in it. I'm thinking of something like that:
@(template: PlayScalaViewTemplate = defaultTemplate())
Thanks!
Upvotes: 1
Views: 448
Reputation: 10401
Yes you can. It's very simple once you discover that Play templates are just functions.
The higher order template (the one that gets the simple template as parameter) would look like this:
higherOrder.scala.html:
@(template: Html => Html)
<html>
<head><title>Page</title></head>
<body>
@template {
<p>This is rendered within the template passed as parameter</p>
}
</body>
</html>
So, if you have a simple sub-template like
simple.scala.html:
@(content: Html)
<div>
<p>This is the template</p>
@content
</div>
you would apply the template in the controller like so:
def index = Action {
Ok(views.html.higherOrder(html => views.html.simple(html)))
}
The result would be:
<html>
<head><title>Page</title></head>
<body>
<div>
<p>This is the template</p>
<p>This is rendered within the template passed as parameter</p>
</div>
</body>
</html>
So, scala templates are ultimately functions so you can compose them like functions.
Upvotes: 4