首页 > 解决方案 > 在刀片模板中组织组件的最佳方式

问题描述

假设我有一个包含不同帖子和评论的博客。现在我想在我网站的不同页面上显示帖子。在大多数教程中,他们是这样的:

@foreach ($posts as $post)
    <div class="post">
      <h2>{{$post->title}}</h2>
      [...]
    </div>
@endforeach

这似乎很好,当您只有一页时,您想在其中显示帖子。但是,如果您有多个具有相同组件的页面怎么办?当然,您可以使用刀片 @component 功能。但是这种方法的性能如何?

假设我有多个要显示帖子的部分。也许我的帖子我有多个视图变体。这样的事情可以吗?

index.blade.php

@extends('layouts.app')

@section('content')
    @component("section")
       @foreach ($posts as $post)
           @component("post", ["post" => $post])@endcomponent
       @endforeach
    @endcomponent

    @component("section")
       @foreach ($posts as $post)
           @component("post[highlight]", ["post" => $post])@endcomponent
       @endforeach
    @endcomponent
@endsection

section.blade.php

<section>{{ $slot }}</section>

post.blade.php

<div class="post {{css}}">
    <h2>{{$post->title}}</h2>
    [...]
</div>

发布[高亮].blade.php

@component("post", ["post" => $post, "css" => "highlight"])@endcomponent

这将减少依赖关系并且模板将是干净的。但在我看来,这不是组织刀片模板的常用方法。

标签: phplaravellaravel-blade

解决方案


建议你在里面做循环,section.blade.php每次使用都可以重复访问帖子列表

@component('section')
...
@endcomponent

如果你想使用组件在不同的布局中加载不同的列表,最好的使用方式是@slot()

@slot('post')
...
@endslot

现在,插槽需要$post组件刀片文件中的变量(即section.blade.php)。您应该设法$post从循环中返回一个变量。

也许这将对组件和插槽有所帮助


推荐阅读