按视图显示内容

Displaying content by view

我是 Laravel 和 Blade 的新手。我有两个不同的内容,一个用于主页,第二个用于任何视图,不包括主页。

我有这段代码,但没有任何反应:

@if(view('home')) // Display content if is home, display 'foo'
    @include('partials/foo')
@else
    @include('partials/bar') // Okay, not in home, display 'bar'
@endif;

这是正确的方法吗?

在blade中使用Routeclass获取方法,根据方法决定

@if(\Route::getCurrentRoute()->getActionMethod()  == 'index')
    @include('partials/foo')
@else
   @include('partials/bar') // Okay, not in home, display 'bar'
@endif;

我用这个How to get the current URL inside @if statement (blade) in Laravel 4?

解决了
@if(Request::is('/')) // Homepage
    'foo'
@else // All pages
    'bar'
@endif

通常,您会使用控制器。流程如下:

  • 你的routes.web文件有一个路由,比如/home
  • this指向控制器上的一个public方法,例如HomeController@index()
  • 控制器进行任何查询和计算,然后returns一个包含所需数据的视图

在routes.web中:

Route::get('home', 'HomeController@index');

在家庭控制器中class:

public function index()
{
    $variable = ModelName::where('field', 'value')->first();

    return view('home')->with('variable', $variable);
}

这使您不必检查 blade 中的视图,因为您专门将它发送到那里。

如果不需要,请删除变量内容。