php - 在刀片模板中组织组件的最佳方式
问题描述
假设我有一个包含不同帖子和评论的博客。现在我想在我网站的不同页面上显示帖子。在大多数教程中,他们是这样的:
@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
现在,插槽需要$post
组件刀片文件中的变量(即section.blade.php
)。您应该设法$post
从循环中返回一个变量。
也许这将对组件和插槽有所帮助
推荐阅读
- rabbitmq - Spring AMQP RabbitMQ RPC 优先队列
- c# - 如何在 C# 中将命名空间添加到肥皂信封
- php - 如何使用 php 7.0 和 laravel 5.5 生成二维码
- c# - MVC SlidingExpiration 和验证 Post Requets
- python - 使用python从Excel文件中读取表格数据
- angular - 没有从角管和水龙头触发的功能
- oracle - ORA-00942 在 EXECUTE IMMEDIATE 创建表后引用表时出错
- android - 错误:找不到 com.google.gms:google-services:4.2.0
- flutter - How to test Flutter widgets on different screen sizes?
- excel - 动态标签颜色问题