Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Twirl

Twirl is the templating engine used by the Play Framework for generating dynamic HTML content. It allows developers to write Scala code within HTML templates, which makes it possible to render dynamic data on web pages efficiently. Here's a basic tutorial to get you started with Twirl in a Play Framework application:

Step 1: Understanding Twirl Template Syntax

Twirl templates are basically HTML files with Scala code embedded in them. The files have a .scala.html extension and are located in the app/views directory of a Play project. The syntax for embedding Scala code is straightforward:

  • @expression to output the value of an expression.
  • @{code block} for more complex Scala code.
  • @for(item <- items) { ... } to iterate over collections.
  • @if(condition) { ... } for conditionals.

Step 2: Create a Twirl Template

  1. Navigate to the app/views directory.
  2. Create a new file named hello.scala.html.
  3. Add the following content to create a simple template that takes a String parameter and displays a greeting:
@(name: String)

<!DOCTYPE html>
<html>
<head>
    <title>Hello, @name!</title>
</head>
<body>
    <h1>Hello, @name!</h1>
</body>
</html>

This template expects a name parameter and uses it to display a greeting.

Step 3: Use the Template in a Controller

Now, let's use this template in a controller to render a dynamic web page:

  1. Open or create a controller in the app/controllers directory, for example, HomeController.scala.
  2. Add a new action method that renders the hello template with a name:
package controllers

import play.api.mvc._

class HomeController @Inject()(val controllerComponents: ControllerComponents) extends BaseController {

  def hello(name: String) = Action { implicit request: Request[AnyContent] =>
    Ok(views.html.hello(name))
  }
}

This controller action calls the hello template, passing a name parameter to it, and returns the rendered HTML as an Ok HTTP response.

Step 4: Define a Route

To make the new action accessible via HTTP, you need to define a route:

  1. Open the conf/routes file.
  2. Add a new route definition for the hello action:
GET     /hello/:name      controllers.HomeController.hello(name)

This route maps GET requests to /hello/[name] to the hello action in the HomeController, passing the [name] part of the URL as a parameter.

Step 5: Test Your Application

  1. Start your Play application by running sbt run from the terminal in your project's root directory.
  2. Open a web browser and navigate to http://localhost:9000/hello/YourName, replacing YourName with any name you wish.
  3. You should see the greeting displayed on the page, dynamically generated by the Twirl template.