使用拉拉维尔刀片模板系统的正确可重用子视图


Proper Reusable Subview with Laravel's Blade Template System

我有一个登录表单,我希望在各种上下文中重复使用。例如,我想要一个只有登录名(www.mysite.com/login)的页面,但也想使用我的首页上的登录表单(wwww.mysite.com)。

Laravel的文档提出了以下方法来使用用户配置文件的子视图。

<!-- Stored in app/controllers/UserController.php -->
class UserController extends BaseController {
    /**
     * The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';
    /**
     * Show the user profile.
     */
    public function showProfile()
    {
        $this->layout->content = View::make('user.profile');
    }
}
<!-- Stored in app/views/layouts/master.blade.php -->
<html>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show
        <div class="container">
            @yield('content')
        </div>
    </body>
</html>
<!-- Stored in app/views/user/profile.blade.php -->
@extends('layouts.master')
@section('sidebar')
    <p>This is appended to the master sidebar.</p>
@stop
@section('content')
    <p>This is my body content.</p>
@stop
问题是子视图

被代码"污染",使其成为layouts.master视图的子视图。由于我希望我的登录表单可以在各种布局中重复使用,因此我不希望引用应该使用它的特定布局。

我想我可以在视图中将其称为视图变量:

{{ $login }}

然后用这样的控制器实现它:

$this->someview->login = View::make('user.login');

因此,我的登录视图可以是纯粹的:

 <!-- Stored in app/views/user/login.php -->
<form method="post" action="{{ URL::to('/') }}/login" accept-charset="utf-8">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <fieldset>
        <legend>credentials</legend>
        <label>
            <span>email</span>
            <input name="email" type="email" placeholder="yourname@email.com" tabindex="1" required autofocus>
        </label>
        <label>
            <span>password</span>
            <input name="password" type="password" placeholder="password" tabindex="2" required>
        </label>
    </fieldset>
    <input type="submit" value="login">
</form>

这是插入子视图而不对应使用的布局进行硬编码的最佳方法吗?

老实说,我可以看到为特定视图定义布局的力量,因为它提供了加载视图的可能性,系统会自动找到布局,但这不违背干编码的概念吗?

可以使用

边栏选项卡@include语法将任何视图包含在另一个视图中。Laravel文档(您必须向下滚动一点)

@include('user.login')

如果需要,还可以传入参数...

@include('user.login', array('foo' => 'bar'))

。然后可以在包含的视图中作为变量访问

{{ $foo }}

更新

因此,例如,对于您的登录页面,您将创建一个login.blade.php。(我会将包含表单的登录子视图放在子目录中。 partials

@extends('layouts.master')
@section('content')
    @include('partials.login')
@stop

在控制器操作中,您只需返回登录(页面)视图

return View::make('login'); // NOT partials.login

对于其他需要登录表单的页面,只需执行确切的操作即可。