【问题标题】:Nested comments with Blade in Laravel在 Laravel 中使用 Blade 嵌套评论
【发布时间】:2015-04-30 05:02:41
【问题描述】:

我正在尝试在 Laravel 中使用 Blade 生成嵌套的 cmets。似乎我必须制作一个刀片模板,该模板为每个评论预配置了无限的嵌套 cmets,它是子 cmets。但我希望 cmets 自动生成。

这是我的评论模型:

class Comment extends Model {

    protected $table = 'comments';

    public function user()
    {
        return $this->hasOne('App\Models\User', 'id', 'user_id');
    }

    public function post()
    {
        return $this->hasOne('App\Models\Post', 'id', 'post_id');
    }

    public function children()
    {
        return $this->hasMany('App\Models\Comment', 'parent_id', 'id');
    }

}

在我看来我正在做

@foreach($comments as $comment)
<!-- Comment markup -->
    @if($comment->children->count() > 0)
        @foreach($comment->children as $child)
        <!-- Child comment markup -->
        @if($child->children->count() > 0) // I have to do this unlimited times
            @foreach ....

            @endforeach
        @endif
    @endif
@endforeach

我正在寻找一种方法来自动执行此操作,可能使用函数或其他东西。

【问题讨论】:

标签: php laravel blade


【解决方案1】:

您基本上是在寻找递归视图。这在下面的示例中进行了说明(实际上并不需要提取 show 视图,但这是个好主意)。

资源/视图/cmets/index.blade.php

@foreach($comments as $comment)
    {{-- show the comment markup --}}
    @include('comments.show', ['comment' => $comment])

    @if($comment->children->count() > 0)
        {{-- recursively include this view, passing in the new collection of comments to iterate --}}
        @include('comments.index', ['comments' => $comment->children])
    @endif
@endforeach

资源/视图/cmets/show.blade.php

<!-- Comment markup -->

【讨论】:

  • 感谢您的回答。但我已经想通了。我写了一个类,它为给定的父 ID 和他们的孩子生成标记。它基本上是在做你说的,但更进一步。
  • @ssangki - 您应该在此处包含您的解决方案作为答案
猜你喜欢
  • 2015-09-01
  • 2015-03-26
  • 1970-01-01
  • 2021-09-09
  • 2018-09-20
  • 2013-06-01
  • 2017-01-09
  • 2021-07-24
  • 2018-03-07
相关资源
最近更新 更多