crhayes / blade-partials
此包的最新版本(1.1)没有可用的许可证信息。
1.1
2014-07-11 16:57 UTC
Requires
- php: >=5.3.0
- illuminate/support: 4.x
This package is not auto-updated.
Last update: 2024-09-14 15:37:26 UTC
README
此包引入了blade模板中部分(不是include)的概念。可以将其视为在视图内嵌的@extends功能。
部分允许您扩展视图并向其中注入内容,在视图内直接注入。
为什么?
为了更容易地创建可重用组件。我经常在使用Bootstrap或Foundation等框架时重复大量的HTML样板代码,而此包可以减少这种情况。此外,如果我们需要更改标记,我们不需要在代码中的每个实例中寻找来这样做(DRY)。
此功能可以通过使用@include
实现,但当模板分解成许多分散的微小模板时可能会很烦人。
安装
首先通过Composer安装此包。
{ "require": { "crhayes/blade-partials": "0.*" } }
接下来打开app/config/app.php
,注释掉Illuminate View Service Provider,并添加此包中的服务提供者
'providers' => array( //'Illuminate\View\ViewServiceProvider', ... 'Crhayes\BladePartials\ViewServiceProvider', )
就这样!
创建部分
部分以@partial('path.to.view')
指令开始,该指令接受要扩展的部分视图,并以@endpartial
指令结束。
@partial('partials.panel') @block('title', 'This is the panel title') @block('body') This is the panel body. @endblock @endpartial
部分内的块的行为与模板中的部分相同。它们捕获将被渲染到扩展视图中的数据片段。
渲染部分
我们使用@render('block-to-render')
指令来渲染通过相应的@block
指令提供的内容块。请注意,我们也可以提供默认值。
<div class="panel"> <div class="panel-heading"> <h3 class="panel-title">@render('title', 'Default Title')</h3> </div> <div class="panel-body"> @render('body', 'Default Body') </div> </div>
完整示例
此示例将包含我们的部分HTML文件。请注意,我们可以创建任意多个部分的实例。
// index.blade.php @extends('layouts.master') @section('content') @partial('partials.panel') @block('title', 'This is the panel title') @block('body') This is the panel body. @endblock @endpartial @partial('partials.panel') @block('title', 'This is a second panel title') @block('body') And we will have different content in this body. @endblock @endpartial @stop // /partials/panel.blade.php <div class="panel"> <div class="panel-heading"> <h3 class="panel-title">@render('title')</h3> </div> <div class="panel-body"> @render('body') </div> </div>
嵌套部分
您还可以通过嵌套部分做一些很酷的事情。例如
// index.blade.php @extends('layouts.master') @section('content') @partial('partials.danger-panel') @block('title', 'This is the panel title') @block('body') This is the panel body. @endblock @endpartial @stop // partials/danger-panel.blade.php @partial('partials.panel') @block('type', 'danger') @block('title') Danger! @render('title') @endblock @endpartial // partials/panel.blade.php <div class="panel panel-@render('type', 'default')"> <div class="panel-heading"> <h3 class="panel-title">@render('title')</h3> </div> <div class="panel-body"> @render('body') </div> </div>