如何使用树枝递归显示评论?

How to recursively display comments using twig?

我正在使用 Silex 框架重写一个应用程序。在此应用程序中,用户可以对帖子和评论进行评论。在非MVC应用中,受到this question的启发,我是这样写的:

function display_comments($postid, $parentid=0, $level=0){
   // Get the current comment from DB and display with HTML code
   display_comments($needid, $comment['id'], $level+1);
}

但是,在 Silex 应用程序中,我想从存储库的数据库中检索它们的评论,将其发送到控制器中的树枝模板,最后在模板。这使得以前的解决方案不兼容。

Silex 中这个问题有什么好的解决方案?我应该在视图中放什么,在控制器中放什么,在模型中放什么?

编辑 我现在在控制器中写了函数:

$app->get('/needdetail/{id}', function ($id) use ($app) {
    $need = $app['need']->findNeed($id);

    function display_comments($app, $needid, $comments=array(), $parentid=0, $level=0){
       $replies = $app['comment']->findByNeed($needid, $parentid);
       foreach($replies as $reply){
            $reply['level'] = $level;
            array_push($comments, $reply);
            display_comments($app, $needid, $comments, $reply['id'], $level+1);
       }
       return $comments;
    }

    return $app['twig']->render('needdetail.html', array('need' => $need, 'comments' => display_comments($app, $id)));
})

现在显示 0 级评论,但不显示更深层次的评论。

我设法通过稍微不同的方法获得了所需的结果。控制器和视图都包含一个递归函数:

控制器:

$app->get('/needdetail/{id}', function ($id) use ($app) {
   $need = $app['need']->findNeed($id);

   function get_comments($app, $needid, $parentid=0){
      $comments = array();
      $replies = $app['comment']->findByNeed($needid, $parentid);
      foreach($replies as $comment){
         $comment['replies'] = get_comments($app, $needid, $comment['id']);
         array_push($comments, $comment);    
      }
      return $comments;
   }

   return $app['twig']->render('needdetail.html', array('need' => $need, 'comments' => get_comments($app, $id)));
})

查看:

{% for comment in comments %}
   {% include 'comment.html' with {'level': 0} %}            
{% endfor %}

Comment.html:

<div class="comment">
   //Comment HTML
</div>
{% if comment.replies %}
   {%for reply in comment.replies %}
      {% include 'comment.html' with {'comment': reply, 'level': level+1} %}
   {% endfor %}
{% endif %}