簡體   English   中英

在刀片模板中組織組件的最佳方式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM