使用 Play Framework 2.3.0 检查 Html 片段无效性

c4k*_*c4k 4 templates playframework-2.3 twirl

我的应用程序中有一个具有以下结构的标签:

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

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

我在我的模板中使用它,如下所示:

@tags.Table(5) { } {
    // My content here
}
Run Code Online (Sandbox Code Playgroud)

前面的代码不起作用:即使我让括号为空,也会<thead></thead>显示 。那么如何检查header不为空、null...以及如何在模板中声明我的标签?也许我用 来声明是错误的{ }

如果我用 声明它{},则会出现以下错误:

type mismatch;
 found   : Unit
 required: play.twirl.api.Html
Run Code Online (Sandbox Code Playgroud)

Mic*_*jac 5

twirl 模板编译器将空大括号推断为返回的按值调用参数Unit。你不能只是将大括号留空并期望它通过null

只需传递一个空Html对象作为header,并在打印之前检查 的 是否非空bodyheader

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

并这样称呼它:

@tags.Table(5)(HtmlFormat.empty){
    @* content here *@
}
Run Code Online (Sandbox Code Playgroud)