2

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 ($@product.price)
}

products.scala.html

...
   @display(product)
...

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

Michał Jurczuk
  • 3,728
  • 4
  • 32
  • 56

3 Answers3

6

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 ($@product.price)

views/products.scala.html

...
    @base.display(product)
...
Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
1

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 ($@product.price)

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)
johanandren
  • 11,249
  • 1
  • 25
  • 30
1

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>
biesior
  • 55,576
  • 10
  • 125
  • 182