首页 > 解决方案 > 如何在不重复代码的情况下将数据传输到父模板,

问题描述

我的主布局包含页眉、导航、页脚和许多从他那里继承的刀片模板。我的问题:我有需要在导航栏中连接的类别,也在许多子模板中,也许它可以以某种方式在全球范围内完成而无需重复代码。

这是我的“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

标签: laravel

解决方案


对于这种特殊情况,我建议使用View Composer - 特别是,如果您在该页面上向下滚动一点,您会看到Attaching A Composer To Multiple Views- 您可以使用:

View::composer('*', function ($view) {
    $view->with('categories', App\Category::all());
});

您可以在任何现有提供程序下注册它,例如AppServiceProviderboot方法下:

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        View::composer('*', function ($view) {
            $view->with('categories', App\Category::all());
        });
    }
}

推荐阅读