laravel - 如何在单个视图中处理两个方法

时间:2018-01-22 15:56:14

标签: laravel eloquent

我想在所有页面上放置一个动态横幅部分,而内容也来自所有相关页面上的相应方法,假设主页从方法索引获取数据,从页面获取有关方法的信息:

class PagesController extends Controller
{
    public function index()
    {
      $pages = Page::where('slug', 'home')->first();
      return view('home', compact('pages'));
    }
   public function index()
    {
      $pages = Page::where('slug', 'about')->first();
      return view('home', compact('pages'));
    }
}

但与此同时,我希望从所有页面部分的数据库中获取横幅数据,如:

所有页面都需要此dyanamic横幅部分。那么我将如何将数据传递到此部分,然后将该部分包含在所有视图中?

@section('banner')
how can i get data here, using new method banner? how is it possible to pass data to a section. but not to home view?
@endsection


@section('content')
All pages content coming already here from respective methods.
@endsection

2 个答案:

答案 0 :(得分:0)

嗨,所以你几乎没有选择。

一种是将所有数据,即横幅和内容从控制器发送到视图。所以你会有这样的事情:

class PagesController extends Controller
{
    public function index()
    {
      $pages = Page::where('slug', 'home')->first();
      $someData = 'got this from the db';

      return view('home', [
                'pages' => $pages,
                'banner_data' => $someData
           ]);
    }
}

另一种方法是刀片注射。所以它看起来像这样

@section('banner')
   @inject('VariableName', 'Some\Class\Path')

   {{ $VariableName->getData() }}

@endsection
@section('content')
home page content coming already from index method
@endsection

答案 1 :(得分:0)

我对此的偏好是View Composer。每当我需要页面上的重复元素和/或元素的某些特定逻辑时,它似乎是我的最佳选择。

您基本上可以执行以下操作:

  1. 添加新的ComposerServiceProvider

  2. 在新服务提供商的banner方法中添加boot()作曲家参考。

  3. View::composer( 'banner', 'App\Http\ViewComposers\BannerComposer' );

    1. BannerComposer@compose

    2. 中添加横幅广告素材文件所需的数据
    3. 现在,在您的刀片布局文件或任何其他刀片文件中,您可以@include('banner')显示共享作曲家,其中包括用于呈现模板的数据以及用于呈现模板的特定标记。横幅。