Files
kiri-router/src/Blade/README.md
T
2025-12-01 06:39:04 +08:00

3.8 KiB
Raw Blame History

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
  • 编译缓存:自动缓存编译后的模板以提高性能

使用方法

基本用法

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. 变量输出

<!-- 转义输出 -->
<h1>{{ $title }}</h1>
<p>{{ $description }}</p>

<!-- 原始输出(不转义) -->
<div>{!! $htmlContent !!}</div>

2. 条件语句

@if($user->isAdmin())
    <p>管理员</p>
@elseif($user->isModerator())
    <p>版主</p>
@else
    <p>普通用户</p>
@endif

3. 循环

@foreach($users as $user)
    <div>
        <h3>{{ $user->name }}</h3>
        <p>{{ $user->email }}</p>
    </div>
@endforeach

@for($i = 0; $i < 10; $i++)
    <p>Item {{ $i }}</p>
@endfor

4. 布局继承

layouts/app.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>@yield('title', '默认标题')</title>
</head>
<body>
    <header>
        @include('components.header')
    </header>
    
    <main>
        @yield('content')
    </main>
    
    <footer>
        <p>&copy; 2024</p>
    </footer>
</body>
</html>

user/profile.blade.php:

@extends('layouts.app')

@section('title')
    用户资料
@endsection

@section('content')
    <h1>用户资料</h1>
    <p>姓名:{{ $name }}</p>
    <p>邮箱:{{ $email }}</p>
@endsection

5. 包含视图

@include('components.header')

@include('components.footer', ['year' => 2024])

6. 注释

{{-- 这是注释,不会输出到 HTML --}}

7. 原始 PHP

@php
    $count = count($items);
    $total = array_sum($prices);
@endphp

<p>总数:{{ $count }}</p>

高级用法

自定义指令

use Kiri\Router\Blade\BladeHelper;

$factory = BladeHelper::getFactory();

// 注册自定义指令
$factory->directive('datetime', function ($expression) {
    return "<?php echo date('Y-m-d H:i:s', {$expression}); ?>";
});

使用自定义指令:

@datetime(time())

共享数据

use Kiri\Router\Blade\BladeHelper;

$factory = BladeHelper::getFactory();

// 共享数据到所有视图
$factory->share('siteName', 'My Website');
$factory->share([
    'version' => '1.0.0',
    'author' => 'Kiri Team'
]);

清除缓存

use Kiri\Router\Blade\BladeHelper;

$factory = BladeHelper::getFactory();
$factory->clearCache();

配置

视图路径和缓存路径可以通过常量配置:

// 视图路径
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. 建议在生产环境中定期清理缓存目录