在Laravel中模板化

cor*_*ryj 27 php laravel laravel-3

我正在尝试让我的默认模板与Laravel一起使用.我来自Codeigniter和Phil Sturgeon的模板系统,所以我试图以类似的方式做到这一点.任何人都可以帮我解决我错过/做错的事吗?谢谢!

//default.blade.php (located in layouts/default)
<html>
    <title>{{$title}}</title>
    <body>
    {{$content}}
    </body>
</html>
//end default.blade.php

//home.blade.php (index view including header and footer partials)
@layout('layouts.default')
@include('partials.header')
//code
@include('partials.footer')
//end home

//routes.php (mapping route to home controller)
Route::controller( 'home' );
//end

//home.php (controller)
<?php
class Home_Controller extends Base_Controller {
    public $layout = 'layouts.default';
    public function action_index()
    {   
        $this->layout->title = 'title';
        $this->layout->content = View::make( 'home' );
    }
}
//end
Run Code Online (Sandbox Code Playgroud)

小智 85

你正在混合两种不同的Laravel布局方法.这样您就可以渲染布局视图,包含主视图并尝试再次包含内部布局.

我个人的偏好是控制器方法.

控制器布局

控制器和布局可以保持不变.

注意:作为一种快捷方式,您可以嵌套内容而不是View :: make,当您在布局中回显它时,它会自动呈现它.

在home.blade.php中删除@layout函数.

编辑(示例):

控制器/ home.php

<?php
class Home_Controller extends Base_Controller {
  public $layout = 'layouts.default';
  public function action_index()
  {
    $this->layout->title = 'title';
    $this->layout->nest('content', 'home', array(
      'data' => $some_data
    ));
  }
}
Run Code Online (Sandbox Code Playgroud)

视图/布局/ default.blade.php

<html>
  <title>{{ $title }}</title>
  <body>
    {{ $content }}
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

意见/ home.blade.php

部分内容包含在内容中.

@include('partials.header')
{{ $data }}
@include('partials.footer')
Run Code Online (Sandbox Code Playgroud)

刀片布局

如果你想要这种方法,你会遇到一些问题.首先,您将在布局后包含新内容.不确定是否有意,但@layout函数本身只是一个@include限制在视图的最开头.因此,如果您的布局是一个封闭的html,那么之后的任何包含都将在您的html布局之后附加.

您的内容应使用@section函数和@yield在您的布局中使用.页眉和页脚可以包含在@include的布局中,或者如果你想在内容视图中定义它,那么也将它们放在@section中,如下所示.如果你以某种方式定义它,如果一个部分不存在则不会产生任何结果.

控制器/ home.php

<?php
class Home_Controller extends Base_Controller {
  public function action_index()
  {
    return View::make('home')->with('title', 'title');
  }
}
Run Code Online (Sandbox Code Playgroud)

视图/布局/ default.blade.php

<html>
 <title>{{$title}}</title>
 <body>
  @yield('header')
  @yield('content')
  @yield('footer')
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

意见/ home.blade.php

@layout('layouts.default')
@section('header')
  header here or @include it
@endsection
@section('footer')
  footer
@endsection
@section('content')
  content
@endsection
Run Code Online (Sandbox Code Playgroud)