Maik Klein
Maik Klein

Reputation: 16148

Java Play2 - Generic templates?

is it possible to create generic templates?

Pseudo code:

@(myForm: Form[T])

So I can reuse them like this:

@inputText(
                myForm("title"), 
                '_label -> "title"

            )

Upvotes: 7

Views: 1087

Answers (3)

virtualeyes
virtualeyes

Reputation: 11237

I don't like the @(form: Form[_]) approach as it is throws type safety out the window.

When passing in ok(form.render(userform)), you'll get no help from the compiler when you @form("lastNme") in your template, but you will get a runtime error if not caught during testing.

What I'm doing is supplying an interface (or trait in play 2 scala) for common forms (e.g. membership signup and conference registration, or league stats and team stats, etc.); that way, at compile time, fat fingered typos and the like are caught.

Yes, more boilerplate to deal with, but coming from the dynamic language side of the fence, the less I have to deal with runtime errors the better...

Upvotes: 4

Marius Soutier
Marius Soutier

Reputation: 11274

Use the magic underscore for that:

@(form: Form[_])

This is called an existential type in Scala, it roughly means "there exists a type parameter but I don't care what it is".

Upvotes: 9

biesior
biesior

Reputation: 55798

Did you try?

in the app/views package create new vies: pseudo.scala.html

@(someParam: String)
<h1>This is my pseudo template</h1>
<div>And there is some param: <b>@someParam</b></div>

Then in any other view you can use it like this:

...
<div>@pseudo("param pam pam")</div>
...

Of course your param(s) don't need to be String only, so you can pass there, Form[T], List[T], or whatever else.

Upvotes: 2

Related Questions