Recursive blocks in Scala Play Framework templates

I am writing a blog post template that has comments. The natural way of writing a template for streaming comments uses a recursive way to build Html. Something like that:

@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 gives an error:

An error occurred: the recursive showComment method requires a result type

If I try to put the return type in showComment, it calls this message:

An error occurred: not found: showComment value

Any workaround?

+6
source share
3 answers

This works for me:

Enter the code in @{}

 @{ //use regular scala here: def showComment(comment: models.Comment):Node = { .... } //the above just declared a recursive method, now call it: showComment(...) } 
  • define a recursive method
  • method call at the end of the block
  • profit!
+4
source

I managed to get past this by moving the recursive template to my own file.

+1
source

In Scala, a recursive method requires a return type: See Why does Scala require a return type for recursive functions?

I don't know much (nothing else) 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> } 
0
source

Source: https://habr.com/ru/post/898934/


All Articles