# Kiri Blade 模板引擎 这是一个类似 Laravel Blade 的模板引擎实现,用于 kiri-router 项目。 ## 功能特性 - ✅ 变量输出:`{{ $variable }}` 和 `{!! $variable !!}` - ✅ 控制结构:`@if`, `@elseif`, `@else`, `@endif` - ✅ 循环:`@foreach`, `@endforeach`, `@for`, `@endfor`, `@while`, `@endwhile` - ✅ 布局继承:`@extends`, `@section`, `@yield`, `@endsection` - ✅ 包含视图:`@include` - ✅ 注释:`{{-- comment --}}` - ✅ 原始 PHP:`@php ... @endphp` - ✅ 编译缓存:自动缓存编译后的模板以提高性能 ## 使用方法 ### 基本用法 ```php use function Kiri\Router\View; // 在控制器中渲染视图 return View('user.profile', [ 'name' => 'John Doe', 'email' => 'john@example.com' ]); ``` ### 视图文件结构 视图文件应放在 `resources/view` 目录下,使用 `.blade.php` 扩展名: ``` resources/ view/ layouts/ app.blade.php user/ profile.blade.php components/ header.blade.php ``` ### 模板语法示例 #### 1. 变量输出 ```blade
{{ $description }}
管理员
@elseif($user->isModerator())版主
@else普通用户
@endif ``` #### 3. 循环 ```blade @foreach($users as $user){{ $user->email }}
Item {{ $i }}
@endfor ``` #### 4. 布局继承 **layouts/app.blade.php:** ```blade姓名:{{ $name }}
邮箱:{{ $email }}
@endsection ``` #### 5. 包含视图 ```blade @include('components.header') @include('components.footer', ['year' => 2024]) ``` #### 6. 注释 ```blade {{-- 这是注释,不会输出到 HTML --}} ``` #### 7. 原始 PHP ```blade @php $count = count($items); $total = array_sum($prices); @endphp总数:{{ $count }}
``` ## 高级用法 ### 自定义指令 ```php use Kiri\Router\Blade\BladeHelper; $factory = BladeHelper::getFactory(); // 注册自定义指令 $factory->directive('datetime', function ($expression) { return ""; }); ``` 使用自定义指令: ```blade @datetime(time()) ``` ### 共享数据 ```php use Kiri\Router\Blade\BladeHelper; $factory = BladeHelper::getFactory(); // 共享数据到所有视图 $factory->share('siteName', 'My Website'); $factory->share([ 'version' => '1.0.0', 'author' => 'Kiri Team' ]); ``` ### 清除缓存 ```php use Kiri\Router\Blade\BladeHelper; $factory = BladeHelper::getFactory(); $factory->clearCache(); ``` ## 配置 视图路径和缓存路径可以通过常量配置: ```php // 视图路径 define('APP_PATH', __DIR__ . '/'); // 缓存路径(可选) define('RUNTIME_PATH', __DIR__ . '/runtime'); ``` 默认情况下: - 视图路径:`APP_PATH . 'resources/view'` - 缓存路径:`RUNTIME_PATH . '/blade'` 或系统临时目录 ## 注意事项 1. 模板文件必须使用 `.blade.php` 扩展名 2. 视图路径使用点号分隔,如 `user.profile` 对应 `user/profile.blade.php` 3. 编译后的模板会自动缓存,修改源文件后会自动重新编译 4. 建议在生产环境中定期清理缓存目录