Recursive blocks in Scala Play Framework templates
I'm writing a template for a blog post, which has threaded comments. A natural way of writing a template for threaded comments it use a recursive way for constructing the Html. Something like this:
@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>
}
The problem开发者_开发百科 is that using a recursive block yields the error:
Error raised is : recursive method showComment needs result type
If I try to put a return type in the showComment it raises this errror:
Error raised is : not found: value showComment
Any workaround?
This works for me:
Enclose code in @{}
@{
//use regular scala here:
def showComment(comment: models.Comment):Node = {
....
}
//the above just declared a recursive method, now call it:
showComment(...)
}
- define recursive method
- call the method at the end of the block
- profit !
I was able to get past this by moving the recursive template into its own file.
In Scala, recursive method require a return type: See Why does Scala require a return type for recursive functions?
I don't know much (more like nothing) about the Play Framework but try:
@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>
}
精彩评论