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

Solutions

1. Hello World

Create a file named hello.scala.html in your app/views directory. This template should accept a single string parameter and display it in an HTML paragraph.

@(name: String)

<!DOCTYPE html>
<html>
<head>
    <title>Hello World Example</title>
</head>
<body>
    <p>Hello, @name!</p>
</body>
</html>

2. List Rendering

Create a file named listRendering.scala.html in your app/views directory. This template will accept a List of strings and render them in an unordered list. It will display a message if the list is empty.

@(items: List[String])

<!DOCTYPE html>
<html>
<head>
    <title>List Rendering Example</title>
</head>
<body>
    @if(items.isEmpty) {
        <p>No items to display.</p>
    } else {
        <ul>
            @for(item <- items) {
                <li>@item</li>
            }
        </ul>
    }
</body>
</html>

3. Form Submission Display

For this exercise, you'll need a controller to handle the form submission and two Twirl templates: one for the form and another to display the submitted data.

Form Template (userForm.scala.html):

@(formAction: Call)

<!DOCTYPE html>
<html>
<head>
    <title>User Form</title>
</head>
<body>
    <form action="@formAction" method="POST">
        <div>
            <label for="firstName">First Name:</label>
            <input type="text" id="firstName" name="firstName">
        </div>
        <div>
            <label for="lastName">Last Name:</label>
            <input type="text" id="lastName" name="lastName">
        </div>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Display Template (displayUser.scala.html):

@(firstName: String, lastName: String)

<!DOCTYPE html>
<html>
<head>
    <title>Display User</title>
</head>
<body>
    <p>First Name: @firstName</p>
    <p>Last Name: @lastName</p>
</body>
</html>

Controller Methods (Scala):

In your controller, you will need to add methods to render the form and handle the submission. This example assumes you are using a Scala controller.

import play.api.mvc._
import javax.inject._

class UserController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
  
  def showForm = Action { implicit request: Request[AnyContent] =>
    Ok(views.html.userForm(routes.UserController.handleSubmit))
  }

  def handleSubmit = Action { implicit request: Request[AnyContent] =>
    val postVals = request.body.asFormUrlEncoded
    val firstName = postVals.get("firstName").flatMap(_.headOption).getOrElse("")
    val lastName = postVals.get("lastName").flatMap(_.headOption).getOrElse("")
    Ok(views.html.displayUser(firstName, lastName))
  }
}

Ensure your routes file (conf/routes) includes the necessary routes for these actions:

GET     /form                       controllers.UserController.showForm
POST    /submit-form                controllers.UserController.handleSubmit

4. Conditional Content

Create a file named conditionalContent.scala.html in your app/views directory. This template will display different content based on the Boolean value passed to it.

@(showMessage: Boolean)

<!DOCTYPE html>
<html>
<head>
    <title>Conditional Content Example</title>
</head>
<body>
    @if(showMessage) {
        <p>This is a conditional message shown only when 'showMessage' is true.</p>
    } else {
        <p>This message is shown when 'showMessage' is false.</p>
    }
</body>
</html>

5. Nested Templates

For nested templates, you typically have a main layout template and one or more child templates. Let's create a simple layout template and a child template that uses it.

Main Layout Template (mainLayout.scala.html):

@(title: String)(content: Html)

<!DOCTYPE html>
<html>
<head>
    <title>@title</title>
</head>
<body>
    <header>
        <h1>Site Header</h1>
    </header>

    @content

    <footer>
        <p>Site Footer</p>
    </footer>
</body>
</html>

Child Template (childPage.scala.html):

@()

@mainLayout("Child Page") {
    <p>This is the content of the child page.</p>
}

6. Loop with Conditional

Create a file named loopWithConditional.scala.html in your app/views directory. This template will iterate over a list of integers, displaying each in a list item, and highlight numbers divisible by 3.

@(numbers: List[Int])

<!DOCTYPE html>
<html>
<head>
    <title>Loop with Conditional Example</title>
</head>
<body>
    <ul>
        @for(number <- numbers) {
            <li class="@if(number % 3 == 0) {highlight}">
                @number
            </li>
        }
    </ul>
</body>
</html>

You might also include some CSS within the <head> section or an external stylesheet to style the .highlight class for numbers divisible by 3, like so:

<style>
    .highlight {
        font-weight: bold;
    }
</style>