【问题标题】:Play Framework template doesn't have Html typePlay Framework 模板没有 Html 类型
【发布时间】:2014-10-10 16:03:59
【问题描述】:

我有一个名为 mainBody 的模板,格式如下:

@(title: String)(html: Html, moreScripts: Html = Html(""))

我可以这样称呼它

views.html.mainBody("All properties")(views.html.showProperties(list))

views.html.showProperties() 是另一个模板。我的印象是模板只是返回Html 的函数。但是,如果我将其扩展到:

views.html.mainBody("All properties")(views.html.showProperties(list), views.html.showPropertiesScripts)

views.html.showPropertiesScripts 只是一个带有一些 HTML 代码的模板,我得到了错误:

play.PlayExceptions$CompilationException: Compilation error[type mismatch;
 found   : views.html.showPropertiesScripts.type
 required: play.twirl.api.Html]
        at play.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27) ~[na:na]
        at play.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27) ~[na:na]
        at scala.Option.map(Option.scala:145) ~[scala-library-2.11.2.jar:na]
        at play.PlayReloader$$anon$1$$anonfun$play$PlayReloader$$anon$$taskFailureHandler$1.apply(PlayReloader.scala:234) ~[na:na]
        at play.PlayReloader$$anon$1$$anonfun$play$PlayReloader$$anon$$taskFailureHandler$1.apply(PlayReloader.scala:229) ~[na:na]

我不明白这一点。而不是预期的类型Htmlviews.html.showPropertiesScriptsviews.html.showPropertiesScripts.type?这是什么?为什么views.html.showPropertiesScripts 不是Html 类型(就像我的其他模板一样)?

【问题讨论】:

    标签: scala playframework-2.0


    【解决方案1】:

    mainBody.scala.html这样使用:

    @(title: String, moreScripts: Html = Html(""))(html: Html)
    <!DOCTYPE html>
    <html>
        <head lang="en">
          <title>@title</title>
          @moreScripts
        </head>
        <body>
           @html
        </body>
    </html>
    

    观点:

    @(list: List[YourType])
    
    @moreScripts = {
        <script>alert ('it works')</script>
    }
    
    @mainBody(title = "All properties", moreScripts = moreScripts) {
        @showProperties(list)
    }
    

    moreScripts 是可选的,您可以在其他视图中跳过它:

    @(list: List[YourType])
    
    @mainBody(title = "Other view") {
        @showProperties(list)
    }
    

    【讨论】:

    • 这很有效,而且我比我更喜欢这种风格。但是,你能解释一下为什么这行得通而我的原始代码不行吗?
    • Mike TBH 我从未分析过 Play 的模板引擎,如果您有兴趣,请下载源代码;)一般规则是在第一个括号中声明视图的所有参数(强制和可选),在第二个括号中声明 Html有内容。
    • 好多了。工作。
    【解决方案2】:

    我认为您将“类型”与“返回类型”混淆了。大概是views.html.showPropertiesScripts是一个不带任何参数的模板(它以@()开头)。如果是这种情况,它没有类型Html,而是一个带有def apply(): Html 的类,这就是为什么当你用括号“调用”它时,它会返回Html。您可以将其视为具有() =&gt; Html 类型。你应该试试:

    views.html.mainBody("All properties")(views.html.showProperties(list), views.html.showPropertiesScripts())
    

    您可能对calling a method without a parameter list 的概念感到困惑。这在处理apply 时不起作用,因为如果您关闭参数列表,Scala 会将您解释为引用对象本身,而不是apply 的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多