【问题标题】:Recursive blocks in Scala Play Framework templatesScala Play 框架模板中的递归块
【发布时间】:2011-10-09 21:32:28
【问题描述】:

我正在为博客文章编写一个模板,其中包含线程化的 cmets。为线程化 cmets 编写模板的一种自然方式是使用递归方式构建 Html。像这样的:

@showComment(comment: models.Comment) = {
    <div class="comment">
        <div class="comment-metadata">
            <span class="comment-author">by @comment.author,</span>
            <span class="comment-date">
                @comment.postedAt.format("dd MMM yy")
            </span>
        </div>
        <div class="comment-content">
            <div class="about">Detail: </div>
            @Html(comment.content.replace("\n", "<br>"))
        </div>
        <a href="@action(controllers.Application.replyComment(comment.id()))">Reply</a>
        @comments filter { c => c.parent_id == comment.id } map { 
            c => @showComment(c)
        }
    </div>
}

问题是使用递归块会产生错误:

引发的错误是:递归方法 showComment 需要结果类型

如果我尝试在 showComment 中添加返回类型,则会引发此错误:

引发的错误是:未找到:值 showComment

有什么解决方法吗?

【问题讨论】:

    标签: scala playframework threaded-comments


    【解决方案1】:

    这对我有用:

    @{}中附上代码

    @{
    
        //use regular scala here:
        def showComment(comment: models.Comment):Node = {
        ....
        }
        //the above just declared a recursive method, now call it:
    
       showComment(...)
    
    }
    
    • 定义递归方法
    • 在块的末尾调用方法
    • 利润!

    【讨论】:

      【解决方案2】:

      我可以通过将递归模板移动到它自己的文件中来解决这个问题。

      【讨论】:

        【解决方案3】:

        在 Scala 中,递归方法需要返回类型:参见 Why does Scala require a return type for recursive functions?

        我对 Play 框架了解不多(更像一无所知),但请尝试:

        @showComment(comment: models.Comment):Node = {
        <div class="comment">
            <div class="comment-metadata">
                <span class="comment-author">by @comment.author,</span>
                <span class="comment-date">
                    @comment.postedAt.format("dd MMM yy")
                </span>
            </div>
            <div class="comment-content">
                <div class="about">Detail: </div>
                @Html(comment.content.replace("\n", "<br>"))
            </div>
            <a href="@action(controllers.Application.replyComment(comment.id()))">Reply</a>
            @comments filter { c => c.parent_id == comment.id } map { 
                c => @showComment(c)
            }
        </div>
        }
        

        【讨论】:

        • 播放模板似乎不允许设置返回类型。因此根本没有递归。
        • @FelipeHummel 似乎有限制。如果你返回的是 play.template.Html 而不是 Node 会怎样?
        • 同样的错误:“引发的错误是:未找到:值 showComment”=\
        猜你喜欢
        • 2015-02-11
        • 1970-01-01
        • 2014-03-27
        • 2014-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多