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:
@expressionto 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
- Navigate to the
app/viewsdirectory. - Create a new file named
hello.scala.html. - Add the following content to create a simple template that takes a
Stringparameter 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:
- Open or create a controller in the
app/controllersdirectory, for example,HomeController.scala. - Add a new action method that renders the
hellotemplate 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:
- Open the
conf/routesfile. - Add a new route definition for the
helloaction:
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
- Start your Play application by running
sbt runfrom the terminal in your project's root directory. - Open a web browser and navigate to
http://localhost:9000/hello/YourName, replacingYourNamewith any name you wish. - You should see the greeting displayed on the page, dynamically generated by the Twirl template.