Search code examples
twirl

How to specify that a parameter is optional


I am new to Twirl, and am trying to create a TODO application with play, the way I have it right now, I am trying to send two objects(an ArrayList, and a String). I have wrapped some code in the controller in a try catch. If an exception is caught the template should be rendered with a String, but not the ArrayList, and if no exception is caught, It will return an ArrayList, but not a String. I have tried just passing one as null, but I feel there is a better way to do it. Is there? Here is my Twirl:

@(message: String, tasks: ArrayList[Task])

<!DOCTYPE html>
<html>
<head>
<title>TODO</title>
</head>
<body>
    <h1>TODOs</h1>
    <p>@message</p>
    @for(task <- tasks) {
    <li><@task.task</li> }
</body>
</html>

Solution

  • You could use Options:

    @(maybeMessage: Option[String], maybeTasks: Option[Seq[Task]])
    
    <!DOCTYPE html>
    <html>
    <head>
        <title>TODO</title>
    </head>
    <body>
        <h1>TODOs</h1>
        @for(message <- maybeMessage) {
            <p>@message</p>
        }
        @for(tasks <- maybeTasks) {
            @for(task <- tasks) {
                <li>@task.task</li>
            }
        }
    </body>
    </html>
    

    And then from your controller:

    Ok(views.html.foo(None, Some(Seq(Task("task 1"), Task("task 2")))))
    
    Ok(views.html.foo(Some("Something went wrong."), None))