Creating Play Framework template functions (examples)

When you want to create a Play Framework template function, you can find some examples on the Scala Templates page. There you'll find these first two examples.

First, assuming you have a Product model defined something like this:

case class Product(var name: String, var price: BigDecimal)

The first template looks like this:

@display(product: models.Product) = {
  @product.name ($@product.price)
}
 
<ul>
@products.map { p =>
  @display(product = p)
} 
</ul>

As you can see, the @ symbol is used to precede Scala statements. So, any time you want to create a new statement, or reference a variable, you need to precede it with the @ symbol. (Note that the $ symbol in the display function will be output as a $; it's intended to be part of the output, as are the parentheses around the price.)

Their second example demonstrates that the function (what they refer to as a "reusable block") can be pure Scala code, as opposed to being a mix of Scala and HTML/XML:

@title(text: String) = @{
  text.split(' ').map(_.capitalize).mkString(" ")
}
 
<h1>@title("hello world")</h1>

A simple UL/LI List-rendering example

If you're just getting started with Play Framework templates, I created the following example, which may be a little more simple. First, we define the template function (including an optional comment):

@*-------------------------*@
@* A UL/LI helper function *@
@*-------------------------*@
@ul(list: List[Any]) = {
  <ul>
  @list.map { e =>
    <li>@e</li>
  }
  </ul>
}

Then, somewhere later in the body of our template, we call this function:

@ul(List("apple", "banana", "cherry"))

As you might guess, this emits the following HTML output:

<ul>

 <li>apple</li>

 <li>banana</li>

 <li>cherry</li>

</ul>

Another function

This small template function creates a URL string from the given symbol, where the symbol is a String like "AAPL" or "GOOG": 

@getYahooUrl(symbol: String) = @{
  "http://finance.yahoo.com/q/ks?s=%s+Key+Statistics".format(symbol.trim.toUpperCase)
}

Note the places where I had to include the @ symbol.

I call that function from a later spot in my Play template like this:

<a href="@getYahooUrl(stock.symbol)" target="_blank">Go to Yahoo</a> 

Again, the field stock.symbol will be a String like "AAPL" or "GOOG".

Closing thoughts

I'm not sure why the Play Framework documentation specifically refers to code like this as a reusable block instead of a function; I don't know how the code compiles down. I do know that a Play template is compiled to a function, but I don't know about code blocks like this. I prefer to call them functions, because that's what they look like, and that's how I use them. You declare them with function parameters, then pass parameters in when you call the function.

I'll try to add more examples here over time, but until then, I hope this is helpful.