scalaplayframeworkplayframework-2.2scala-template

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

products.scala.html

...
   @display(product)
...

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


Solution

  • 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)
    ...