krisanalfa / bono-blade

Bono PHP 框架的 Laravel Blade 模板引擎

1.0.0 2015-08-26 04:38 UTC

README

Laravel Blade 模板引擎用于 Bono PHP 框架

注意: BonoBlade 也使用 Blade 模板为 partial 视图

安装

将以下行添加到您的 composer.json 文件中

"require": {
    "krisanalfa/bono-blade": "~0.6.*"
},

配置

将以下行添加到您的配置文件中

'bono.providers' => array(
    '\\KrisanAlfa\\Blade\\Provider\\BladeProvider'
),

// Bono Themeing
'bono.theme' => array(
    'class' => '\\KrisanAlfa\\Theme\\BladeTheme', // You can use another theme that extends from bono
),

// Bono Partial (segment of template)
'bono.partial.view' => '\\KrisanAlfa\\Blade\\BonoBlade',

如果您想更改布局文件名、模板路径或缓存路径,您可以在提供者中添加选项,如下所示

'bono.providers' => array(
    '\\KrisanAlfa\\Blade\\Provider\\BladeProvider' => array(
        'templates.path' => array('pathToTemplatesPath'), // Default is array('../templates')
        'cache.path' => 'pathToCachePath',                // Default is '../cache'
        'layout' => 'customLayoutName',                   // Default is 'layout'
    ),
),

注意: 您可以使用基于 BladeTheme 的任何其他主题,例如 blade foundation。 或者,您也可以创建自己的主题。

基本用法

use Bono\App;

$app = App::getInstance();

$app->get('/', function () use ($app) {
    $app->render('yourTemplateName', array('var' => 'value'));
});

布局示例

<!-- myLayout.blade.php -->
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>@yield('title', 'Devel')</title>
</head>

<body>
    <div>
        @yield('content')
    </div>
</body>
</html>

模板示例

<!-- myTemplate.blade.php -->
@section('title')
New Title
@endsection

@section('content')
<h1>Hello, {{ $name }}!</h1>
@endsection

渲染模板

简单来说,您可以通过在 \Bono\App 实例中调用 render 函数来渲染您的模板。

use Bono\App;

$app = App::getInstance();

$app->get('/', function () use ($app) {
    $app->view->setLayout('myLayout');
    $app->render('myTemplate', array('name' => 'Krisan Alfa Timur'));
});

注意: 请确保您没有添加 .blade.php,否则您的模板将无法找到

结果

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>New Title</title>
</head>

<body>
    <div>
        <h1>Hello, Krisan Alfa Timur!</h1>
    </div>
</body>
</html>

无布局的页面渲染

use Bono\App;

$app = App::getInstance();

$app->get('/', function () use ($app) {
    // This method is same with $app->theme->partial($templateName, $data)
    $app->view->display('myTemplateWithoutLayout', array('name' => 'Krisan Alfa Timur'));
});

使用部分

<!-- Layout, filename: myCustomLayout -->
<html>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>
<!-- Template -->
@extends('myCustomLayout')

@section('sidebar')
    @parent

    <p>This is appended to the master sidebar.</p>
@stop

@section('content')
    <p>This is my body content. Appended to the container.</p>
@stop

注意,继承 Blade 布局的视图只是覆盖布局中的部分。您可以使用 @parent 指令在子视图中包含布局内容,从而允许您向布局部分的内容(如侧边栏或页脚)追加内容。

有时,例如当您不确定是否已定义部分时,您可能希望向 @yield 指令传递一个默认值。您可以将默认值作为第二个参数传递

@yield('content', '<p>Default</p>')

包含子视图

@include('view.name')

您还可以向包含的视图传递数据数组

@include('view.name', array('some'=>'data'))

覆盖部分

默认情况下,部分会追加到部分中存在的任何先前内容。要完全覆盖部分,您可以使用 overwrite 语句

@section('test')
   one
@stop
@section('test')
   two
@stop
@yield('test')

输出为

one

但是,如果您将第二个 @stop 更改为 @overwrite

@section('test')
   one
@stop
@section('test')
   two
@overwrite
@yield('test')

那么以下将输出。

two
  • @overwrite - 结束部分并覆盖它。
  • @stop - 停止向部分注入内容。
  • @show - 在 Blade 模板中呈现当前部分。
  • @append - 停止向部分注入内容并将其追加。

扩展模板以重复使用

<!-- listTemplate -->
@section('header')
My sexy header
@endsection

<div class="container">
    @section('body')
        {{-- some other controll structure to make your page happens --}}
    @endsection

    @section('action')
        <div class="action">
            <button>Edit</button>
            <button>Update</button>
        </div>
    @endsection
</div>

@section('footer')
My shiny footer
@endsection
<!-- Another template that extends listTemplate -->

@extends('listTemplate')

@section('body')
    {{-- some other controll structure to make your page happens --}}
    {{-- some kind that make this page unique --}}

    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum eligendi, totam velit earum assumenda optio accusantium magni est maiores ad inventore expedita nisi minus autem, porro adipisci cupiditate in iure!</p>

    <div class="blue">
        Some bluish content
    </div>
@overwrite

基于此案例,您的 body 部分将被 lorem ipsumbluish content 覆盖。

其他 Blade 控制结构

输出数据

Hello, {{{ $name }}}.

The current UNIX timestamp is {{{ time() }}}.

检查存在后输出数据

有时您可能希望输出一个变量,但不确定该变量是否已设置。基本上,您想这样做

{{{ isset($name) ? $name : 'Default' }}}

然而,而不是编写三元运算符,Blade 允许您使用以下方便的快捷方式

{{{ $name or 'Default' }}}

使用花括号显示原始文本

如果您需要显示一个被花括号包围的字符串,您可以通过在文本前加上 @ 符号来转义 Blade 行为

@{{ This will not be processed by Blade }}

当然,所有用户提供的数据都应被转义或净化。要转义输出,您可以使用三元花括号语法

Hello, {{{ $name }}}.

如果您不想转义数据,您可以使用双花括号

Hello, {{ $name }}.

注意: 在输出用户提供的应用程序内容时要非常小心。始终使用三元花括号语法来转义内容中的任何 HTML 实体。

if 语句

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

@unless (App::getInstance()->auth->check())
    You are not signed in.
@endunless

注意:当您想使用 @if(! functionReturnBool()) 时,会使用 @unless 方法。

循环

@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

@while (true)
    <p>I'm looping forever.</p>
@endwhile

注释

{{-- This comment will not be in the rendered HTML --}}

## 扩展 blade

use Bono\App;

$app = App::getInstance();

$app->view->extend(function($view, $compiler) {
    $pattern = $compiler->createMatcher('datetime');

    return preg_replace($pattern, '$1<?php echo $2->format("m/d/Y H:i:s"); ?>', $view);
});

现在您可以使用 @dateTime($dateValue) 获取您的日期时间值。

createPlainMatcher 方法用于没有参数的指令,如 @endif@stop,而 createMatcher 用于带参数的指令。

use Bono\App;

$app = App::getInstance();

$app->view->extend(function($view, $compiler) {
    $pattern = $compiler->createPlainMatcher('pre');

    return preg_replace($pattern, '<pre>', $view);
});

$app->view->extend(function($view, $compiler) {
    $pattern = $compiler->createPlainMatcher('endpre');

    return preg_replace($pattern, '</pre>', $view);
});

现在您可以在需要时使用 @pre@endpre 来打印你的值。就像这样

@pre
print_r($myPrettyPrintVariable)
@endpre

设置 blade 使用的标签内容

您知道 blade 使用 {{}} 来指定要输出的内容,但这与 Mustache 或您正在使用的某些库冲突。如果您想使用其他标签,可以使用 setContentTags 方法。假设您想使用 [%%] 作为您的标签。

use Bono\App;

$app = App::getInstance();

$app->view->setContentTags('[%', '%]');

那么您的模板可以包含如下代码。

The value of $variable is [% $variable %].

您还可以传递第三个参数作为 true,表示您正在设置标签以 转义 内容。

use Bono\App;

$app = App::getInstance();

$app->view->setContentTags('[%', '%]', true);

然后,您可以使用 [-%%-] 替代 {{{}}}

The HTML tags inside this value would be escaped [%- $variable -%].

注意:您必须在使用视图之前调用 setContentTags 方法。最佳选项是:创建一个 Provider 来准备您所有的 Blade 定制。