[英]Best way to organize components in blade templates
假设我有一个包含不同帖子和评论的博客。 现在我想在我网站的不同页面上显示帖子。 在大多数教程中,他们是这样的:
@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
这将减少依赖性并且模板将是干净的。 但在我看来,这不是组织刀片模板的常用方法。
建议你在section.blade.php
做循环,每次使用都可以重复访问帖子列表
@component('section')
...
@endcomponent
如果您想使用组件以不同的布局加载不同的列表,最好的使用方法是@slot()
为:
@slot('post')
...
@endslot
现在插槽需要组件刀片文件(即section.blade.php
)中的$post
变量。 您应该设法从循环中返回一个$post
变量。
也许这将有助于组件和插槽
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.