Skip to content
This repository has been archived by the owner on Jan 15, 2023. It is now read-only.
刘小乐 edited this page Nov 27, 2017 · 8 revisions

Blade

这是从 Laravel 中抽取的模板引擎,跟常见的做法不同,这是一个独立的模块,不再依赖于 Laravel 的容器或其他任何组件。

安装

使用 Composer 时,只需要执行以下命令即可:

composer require xiaoler/blade

如果你没有使用 Composer,可以将 src 目录复制到你的项目中,然后 require 所有的文件即可。

使用

<?php

require '../src/Autoloader.php';

Xiaoler\Blade\Autoloader::register();

use Xiaoler\Blade\FileViewFinder;
use Xiaoler\Blade\Factory;
use Xiaoler\Blade\Compilers\BladeCompiler;
use Xiaoler\Blade\Engines\CompilerEngine;
use Xiaoler\Blade\Filesystem;
use Xiaoler\Blade\Engines\EngineResolver;

$path = ['/view_path'];         // your view file path, it's an array
$cachePath = '/cache_path';     // compiled file path

$file = new Filesystem;
$compiler = new BladeCompiler($file, $cachePath);

// you can add a custom directive if you want
$compiler->directive('datetime', function($timestamp) {
    return preg_replace('/(\(\d+\))/', '<?php echo date("Y-m-d H:i:s", $1); ?>', $timestamp);
});

$resolver = new EngineResolver;
$resolver->register('blade', function () use ($compiler) {
    return new CompilerEngine($compiler);
});

// get an instance of factory
$factory = new Factory($resolver, new FileViewFinder($file, $path));

// if your view file extension is not php or blade.php, use this to add it
$factory->addExtension('tpl', 'blade');

// render the template file and echo it
echo $factory->make('hello', ['a' => 1, 'b' => 2])->render();

几乎所有 Blade 的特性都被保留了,但是一些专属于 Laravel 的特征被移除了:

  • @inject @can @cannot @lang 关键字被移除了
  • 不支持事件和中间件

文档: http://laravel.com/docs/5.1/blade

感谢 Laravel 和它的创作者们,Laravel 是个伟大的项目。

Clone this wiki locally