Documentation

You are viewing the documentation for the 2.0 release in the 2.0.x series of releases. The latest stable release series is 3.0.x.

§Scala templates common use cases

Templates, being simple functions, can be composed in any way you want. Below are examples of some common scenarios.

§Layout

Let’s declare a views/main.scala.html template that will act as a main layout template:

@(title: String)(content: Html)
<!DOCTYPE html>
<html>
  <head>
    <title>@title</title>
  </head>
  <body>
    <section class="content">@content</section>
  </body>
</html>

As you can see, this template takes two parameters: a title and an HTML content block. Now we can use it from another views/Application/index.scala.html template:

@main(title = "Home") {
    
  <h1>Home page</h1>
    
}

Note: We sometimes use named parameters(like @main(title = "Home"), sometimes not like @main("Home"). It is as you want, choose whatever is clearer in a specific context.

Sometimes you need a second page-specific content block for a sidebar or breadcrumb trail, for example. You can do this with an additional parameter:

@(title: String)(sidebar: Html)(content: Html)
<!DOCTYPE html>
<html>
  <head>
    <title>@title</title>
  </head>
  <body>
    <section class="sidebar">@sidebar</section>
    <section class="content">@content</section>
  </body>
</html>

Using this from our ‘index’ template, we have:

@main("Home") {
  <h1>Sidebar</h1>

} {
  <h1>Home page</h1>

}

Alternatively, we can declare the sidebar block separately:

@sidebar = {
  <h1>Sidebar</h1>
}

@main("Home")(sidebar) {
  <h1>Home page</h1>

}

§Tags (they are just functions, right?)

Let’s write a simple views/tags/notice.scala.html tag that displays an HTML notice:

@(level: String = "error")(body: (String) => Html)
 
@level match {
    
  case "success" => {
    <p class="success">
      @body("green")
    </p>
  }

  case "warning" => {
    <p class="warning">
      @body("orange")
    </p>
  }

  case "error" => {
    <p class="error">
      @body("red")
    </p>
  }
    
}

And now let’s use it from another template:

@import tags._
 
@notice("error") { color =>
  Oops, something is <span style="color:@color">wrong</span>
}

§Includes

Again, there’s nothing special here. You can just call any other template you like (and in fact any other function coming from anywhere at all):

<h1>Home</h1>
 
<div id="side">
  @common.sideBar()
</div>

Next: HTTP form submission and validation