【问题标题】:Layout folder for Laravel 4 BladeLaravel 4 Blade 的布局文件夹
【发布时间】:2014-03-20 15:27:45
【问题描述】:

我有一个包含页脚和页眉的“基本”模板:

// Current file is called 'base.blade.php'

// header.blade.php
@include('header')

@yield('body')

// header.blade.php
@include('footer')

我设法通过将 base.blade.php 放在“layouts”文件夹中来使模板正常工作。我的特定文件遵循以下结构:

@extends('layouts.base')

@section('body') 

@stop

这行得通。但是,如果我将 header.blade.php 和 footer.blade.php 放在 layouts 文件夹(当前位于 /views 文件夹的根目录中),则模板不起作用。由于它们也是布局的一部分,因此我想将它们包括在其中。

1.) 我该怎么做?

2.) 我怎样才能分开我的特定视图以将它们分开一点,例如,通过控制器或任意逻辑?

例子:

views/
    layout/
    controller_1_views/
    controller_2_views/
    controller_3_views/

【问题讨论】:

    标签: laravel blade


    【解决方案1】:

    @include 语法来自 Laravel 的根视图目录。所以使用以下文件结构:

    views/
      --layout/
      ----base.blade.php
      ----header.blade.php
      ----footer.blade.php
      --controller_1_views/
      --controller_2_views/
      --controller_3_views/
    

    您的base.blade.php 布局文件必须如下所示:

    @include('layout.header')
    @yield('body')
    @include('layout.footer')
    

    注意绝对 layout.* 路径与相对 * 路径。

    【讨论】:

      【解决方案2】:

      这是我的@rinclude 语句,用它来包含当前编译的视图文件目录下的视图文件或它的子目录,在 Laravel 4.2 下可以正常工作

      Blade::extend(function($view, $compiler)
      {
          $viewBasePath = Config::get('view.paths')[0];
          $curCompiledFilePath = $compiler->getPath();
          $paths = explode('/', substr($curCompiledFilePath, strlen($viewBasePath)), -1);
          $basePath = '';
          foreach($paths as $path) {
              $basePath .= $path . '.';
          }
          $basePath = trim($basePath, '.');
          $basePath = "'$basePath.'.";
          $pattern = $compiler->createMatcher('rinclude');
          return preg_replace($pattern, "<?php echo \$__env->make($basePath$2, array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>", $view);
      });
      

      有了这个目录结构,在 index.blade.php 中,我们可以使用@rinclude('foo') 或@rinclude('dir1.foo1')

      -/app/views/my-base-view
                         └── index.blade.php
                         └── foo.blade.php
                         └── /dir1
                                 └── foo1.blade.php
      

      【讨论】:

        猜你喜欢
        • 2013-07-01
        • 1970-01-01
        • 2014-10-14
        • 2021-07-06
        • 1970-01-01
        • 2023-03-23
        • 2013-07-21
        • 1970-01-01
        • 2014-03-10
        相关资源
        最近更新 更多