在Laravel中使用Blade的嵌套注释

时间:2015-02-27 13:04:55

标签: php laravel blade

我试图在Laravel中使用Blade生成嵌套注释。似乎我必须制作一个刀片模板,该模板具有针对每个评论预先配置的无限嵌套注释及其子评论。但我希望评论能够自动生成。

这是我的评论模型:

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

我正在寻找一种自动化方法,可能还有某种功能。

1 个答案:

答案 0 :(得分:7)

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

资源/视图/评论/ 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

资源/视图/评论/ show.blade.php

<!-- Comment markup -->