Examples of Play Framework Twirl template functions

If you ever need to create a Play Framework Twirl template function, here’s an example of how to create and use one. First, create the Twirl function like this:

@fullUrl(uri: String) = @{
    s"http://kbhr.co/$uri"
}

That function creates a complete URL from the URI it’s given.

Later in your template you can call the Twirl template function like this:

<a href="@fullUrl(u.shortUrl)">@u.shortUrl</a>

That’s all you need to do to create and use a function in a Twirl template. For me the only confusing part is (a) remembering the function syntax and (b) understanding where the @ symbols are supposed to be when calling a custom function.

(Note: This example works with the Play Framework 2.6.)

A complete Twirl template example

I hope that helps as is, but if not, here’s the complete source code for a Twirl template that defines and uses two other Twirl functions:

@(session: Session, nodes: Seq[FrontPageNode])(implicit flash: Flash)

@import play.twirl.api.StringInterpolation

@getUri(n: FrontPageNode) = @{
    n.uri
}

@getStatusString(n: FrontPageNode) = @{
    if (n.status == 1) "Enabled" else "Disabled"
}

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/main.css")">
</head>

<body id="blog-posts-list">
<div id="content">

    <h1>Blog Posts (Admin)</h1>

    @* show Flash messages *@
    @flash.data.map{ case (name, value) =>
        <div>@name: @value</div>
    }

    <div id="add-post-button">
        <form method="get" action="@controllers.admin.routes.BlogPostController.add">
            <button type="submit">Add New</button>&nbsp;
            <a href="@controllers.admin.routes.UserController.logout">logout</a>
        </form>
    </div>

    <table>
        <tr>
            <th>Title</th>
            <th>Date Updated</th>
            <th>URI</th>
            <th>Status</th>
            <th>Admin</th>
        </tr>
        @for(n <- nodes) {
        <tr>
            <td><a href="@routes.UrlAliasController.catchAllUriHandler(getUri(n))">@n.title</a></td>
            <td>@n.changed</td>
            <td>@n.uri</td>
            <td>@getStatusString(n)</td>
            <td>
                <a href="@controllers.admin.routes.BlogPostController.edit(n.nid)">edit&nbsp;(@n.nid)</a><br />
                <a href="@controllers.admin.routes.BlogPostController.delete(n.nid)">delete&nbsp;(@n.nid)</a><br />
                <a href="@controllers.admin.routes.BlogPostController.changeStatus(n.nid)">change&nbsp;status&nbsp;(@n.nid)</a>
            </td>
        </tr>
        }
    </table>

    <script src="@routes.Assets.versioned("javascripts/main.js")" type="text/javascript"></script>

</div>

</body>
</html>

In summary, if you wanted to see examples of Play Framework Twirl template functions, I hope these examples are helpful. For more information, see the Play Framework “template engine” documentation.