Michał Jurczuk
Michał Jurczuk

Reputation: 3828

Scala templates import reusable blocks (Play2)

I'm using Play framework 2.2.4 and Scala templates. I have created base Scala template with many code blocks, which I want to use in multiple views. Something like:

base.scala.html

@()

@display(product: Product) = {
  @product.name ([email protected])
}

products.scala.html

...
   @display(product)
...

How can I import such file in view to use @display block?

Upvotes: 2

Views: 2487

Answers (3)

biesior
biesior

Reputation: 55798

Take a look into templating doc, section: Tags (they are just functions right?)

In general you can i.e. move your block to views/tags/displayProduct.scala.html (and use it as common template) so you can use it in ANY view with:

<div class="product">
    @tags.displayProduct(product)
</div>

Upvotes: 1

johanandren
johanandren

Reputation: 11479

Put it in a separate file, display.scala.html and make it the only/actual template, the file name is the fragment/function name:

@(product: Product)

@product.name ([email protected])

if in the same package just call it

@display(product)

or if in another package either use full package name or import it first

@some.package.display(product)

@import some.package.display

@display(product)

Upvotes: 1

Michael Zajac
Michael Zajac

Reputation: 55569

Each view fragment should be in it's own file, with it's own parameters declared there. A Play template is supposed to work like a single function, not many. Instead, create a directory called base, and separate the view fragments into separate files.

views/base/display.scala.html

@(product: Product)

@product.name ([email protected])

views/products.scala.html

...
    @base.display(product)
...

Upvotes: 6

Related Questions