2

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
c4k
  • 3,714
  • 3
  • 34
  • 55

1 Answers1

4

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 *@
}
Michael Zajac
  • 53,182
  • 7
  • 105
  • 130
  • Perfect ! Thanks @LimbSoup – c4k Sep 29 '14 at 09:58
  • You should change `(HtmlFormat.empty)` for `{HtmlFormat.empty}` – Didac Montero Mar 23 '15 at 11:25
  • Note that you may have to trim the content of the body to avoid empty Strings. In my case I used `@if(!header.body.trim.isEmpty)` . See more on https://www.playframework.com/documentation/2.4.x/api/scala/index.html#play.twirl.api.Html – Adrien Be Apr 10 '15 at 12:00