2016年2月16日 星期二

獨立使用Laravel Blade Template Engine

有別於之前獨立使用Socialite 這次我們利用ServiceProvider來設定Laravel Blade Engine

利用composer安裝 illuminate/view

composer require illunimate/view

config.php

require __DIR__.'/vendor/autoload.php';

use Illuminate\Container\Container;
use Illuminate\Events\Dispatcher;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Fluent;
use Illuminate\View\ViewServiceProvider;

$app = new Container();
$app['events'] = new Dispatcher();
$app['config'] = new Fluent();
$app['files'] = new Filesystem();

// 設定view資料夾
$app['config']['view.paths'] = [__DIR__.'/views/'];
// 設定快取資料夾
$app['config']['view.compiled'] = __DIR__.'/compiled/';

// 利用ServiceProvider來初始化View
$serviceProvider = new ViewServiceProvider($app);
// 註冊
$serviceProvider->register();
// boot
$serviceProvider->boot();

Facade::setFacadeApplication($app);

// 設Facade View Alias方便使用
class_alias(View::class, 'View');

views/test.blade.php

@foreach ([1,2,3] as $v)
    {{ $v }}
@endforeach

index.php

require __DIR__.'/config.php';

echo View::make('test')->render();

完整檔案在Github

沒有留言:

張貼留言