Search code examples
templatesplayframework-2.3twirl

Check Html fragment nullity with Play Framework 2.3.0


I have a tag in my application with the following structure :

@(
    columns: Integer
)(header: Html)(body: Html)

<table>
    @if(header != null) {
        <thead>
            <tr>
                @header
            </tr>
        </thead>
    }
    // Body and foot here
</table>

And I use it in my template like this :

@tags.Table(5) { } {
    // My content here
}

The previous code does not work : even if I let the brackets empty, the <thead></thead> is displayed. So how to check that the header is not empty, null... and how to declare my tag in my template ? Maybe I'm wrong declaring it with { } ?

If I declare it with {}, I have the following error :

type mismatch;
 found   : Unit
 required: play.twirl.api.Html

Solution

  • The twirl template compiler is inferring the empty braces as a call-by-value parameter that returns Unit. You can't just leave the braces empty and expect it to pass null instead.

    Simply pass an empty Html object as the header, and check that the body of the header is non-empty before printing it.

    @(columns: Int)(header: Html)(body: Html)
    <table>
        @if(header.body.nonEmpty) {
            <thead>
                <tr>@header</tr>
            </thead>
        }
        @* ... etc .. *@  
    </table>
    

    And call it like this:

    @tags.Table(5)(HtmlFormat.empty){
        @* content here *@
    }