【问题标题】:Best way to organize components in blade templates在刀片模板中组织组件的最佳方式
【发布时间】:2018-11-29 16:58:28
【问题描述】:

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

@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>

post[highlight].blade.php

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

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

【问题讨论】:

  • 性能真的不应该是一个大问题。 Laravel 模板编译为 PHP 并缓存,然后 PHP opcache 将在重复加载时处理其余部分。

标签: php laravel laravel-blade


【解决方案1】:

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

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

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

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

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

也许这对components and slots有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2017-07-04
    • 2018-12-29
    • 1970-01-01
    • 2010-11-03
    • 2010-09-08
    • 2021-11-20
    相关资源
    最近更新 更多