【问题标题】:Check Html fragment nullity with Play Framework 2.3.0使用 Play Framework 2.3.0 检查 Html 片段无效性
【发布时间】:2014-09-25 14:20:39
【问题描述】:

我的应用程序中有一个标签,其结构如下:

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

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

我在我的模板中这样使用它:

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

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

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

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

【问题讨论】:

    标签: templates playframework-2.3 twirl


    【解决方案1】:

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

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

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

    然后这样称呼它:

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

    【讨论】:

    • 完美!谢谢@LimbSoup
    • 您应该将(HtmlFormat.empty) 更改为{HtmlFormat.empty}
    • 请注意,您可能必须修剪正文的内容以避免空字符串。就我而言,我使用了 @if(!header.body.trim.isEmpty) 。查看更多关于playframework.com/documentation/2.4.x/api/scala/…
    猜你喜欢
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    相关资源
    最近更新 更多