laravel - 如何在不重复代码的情况下将数据传输到父模板,
问题描述
我的主布局包含页眉、导航、页脚和许多从他那里继承的刀片模板。我的问题:我有需要在导航栏中连接的类别,也在许多子模板中,也许它可以以某种方式在全球范围内完成而无需重复代码。
这是我的“HomeContoller”返回索引模板,但如果我用$categories
我的主布局返回我的类别,则看不到这个变量
public function index()
{
$posts = Post::paginate(10);
$popularPosts = Post::orderByViews()->take(6)->get();
return view('front.index', ['posts' => $posts, 'popularPosts' => $popularPosts]);
}
现在我$categories
通过这种方法返回到 layout.blade my。
@php
$categories = App\Category::all();
@endphp
解决方案
对于这种特殊情况,我建议使用View Composer - 特别是,如果您在该页面上向下滚动一点,您会看到Attaching A Composer To Multiple Views
- 您可以使用:
View::composer('*', function ($view) {
$view->with('categories', App\Category::all());
});
您可以在任何现有提供程序下注册它,例如AppServiceProvider
在boot
方法下:
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
View::composer('*', function ($view) {
$view->with('categories', App\Category::all());
});
}
}
推荐阅读
- linux - 阻止访问在 Cpanel linux 主机上创建文件或文件夹
- javascript - 在js中获取位置
- xamarin - Xamarin.Android Camera2 API 相机不会出现在默认应用程序中
- javascript - 如何使用 ajax 和 php 通过 url 从我的桌面上传文件到 web 服务器
- python - Python OpenCV获取fitLine的角度方向
- php - 如何获得 DiVs 级别?
- r - R(dplyr 包)- 每组至少一行(随机抽样,每组 10% 行)
- node.js - 如何在特定通道中发送错误消息
- java - 请帮我解释一下,当这些符号组合在一起时,我知道这意味着什么
- python - Django-在 django-admin 中显示记录,包括组、最大计数和时间戳