承接 anunes/an-template 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

anunes/an-template

Composer 安装命令:

composer require anunes/an-template

包简介

A lightweight, modern PHP template engine with intuitive syntax supporting directives, inheritance, sections, and components

README 文档

README

A lightweight, modern PHP template engine with intuitive syntax supporting directives, inheritance, sections, and components.

Features

  • Blade-like syntax - Familiar directives and templating
  • Template inheritance - Extend layouts and yield sections
  • Component system - Reusable UI components with slots
  • Caching - Compiled template caching for performance
  • Error handling - Detailed error reporting with context
  • PSR-4 autoloading - Modern PHP standards compliance
  • No dependencies - Pure PHP implementation

Installation

Install via Composer:

composer require anunes/an-template

Quick Start

Basic Setup

use AnTemplate\AnTemplate;

// Initialize the template engine
$templates = new AnTemplate(
    templatesPath: __DIR__ . '/templates',
    cachePath: __DIR__ . '/cache',
    cacheEnabled: true
);

// Render a template
echo $templates->render('welcome', ['name' => 'World']);

Using Helper Functions

// Set up global instance for helper functions
viewer_setup(__DIR__ . '/templates', __DIR__ . '/cache');

// Use Laravel-style view helper
view('welcome', ['name' => 'World']); // Outputs directly

// Or get content as string
$content = viewer_content('welcome', ['name' => 'World']);

Template Syntax

Variables

{{-- Escaped output --}}
{{ $name }}
{{ $user->email ?? 'No email' }}

{{-- Raw output --}}
{!! $htmlContent !!}

{{-- Escaped literals --}}
@{{ This will output: {{ $literal }} }}

Conditionals

@if($user->isActive())
    <p>User is active</p>
@elseif($user->isPending())
    <p>User is pending</p>
@else
    <p>User is inactive</p>
@endif

@unless($user->isBanned())
    <p>Welcome back!</p>
@endunless

@isset($user->profile)
    <p>Profile: {{ $user->profile->name }}</p>
@endisset

@empty($posts)
    <p>No posts found</p>
@endempty

Loops

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

@forelse($posts as $post)
    <article>{{ $post->title }}</article>
@empty
    <p>No posts available</p>
@endforelse

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

@while($condition)
    <p>Processing...</p>
@endwhile

Template Inheritance

Layout (layouts/app.view.php):

<!DOCTYPE html>
<html>
<head>
    <title>@yield('title', 'Default Title')</title>
    @stack('styles')
</head>
<body>
    <header>
        @yield('header')
    </header>

    <main>
        @yield('content')
    </main>

    @stack('scripts')
</body>
</html>

Page template:

@extends('layouts.app')

@section('title', 'Welcome Page')

@section('content')
    <h1>Welcome to our site!</h1>
    <p>Hello {{ $name }}!</p>
@endsection

@push('styles')
    <link rel="stylesheet" href="/css/welcome.css">
@endpush

Components

Component (components/alert.view.php):

<div class="alert alert-{{ $type ?? 'info' }}">
    @if(isset($title))
        <h4>{{ $title }}</h4>
    @endif

    <div class="alert-body">
        {{ $slot }}
    </div>
</div>

Using components:

<x-alert type="success" title="Success!">
    Your profile has been updated.
</x-alert>

{{-- Self-closing --}}
<x-alert type="info" />

{{-- With named slots --}}
<x-card>
    @slot('header')
        <h3>Card Title</h3>
    @endslot

    This is the main card content.
@endcard

Includes

@include('partials.header')
@include('partials.nav', ['active' => 'home'])

Raw PHP

@php
    $processed = array_map('strtoupper', $items);
    $total = count($processed);
@endphp

<p>Processing {{ $total }} items</p>

Stacks

@push('scripts')
    <script src="/js/analytics.js"></script>
@endpush

@push('scripts')
    <script src="/js/app.js"></script>
@endpush

{{-- In layout --}}
@stack('scripts')

Directory Structure

your-project/
├── templates/
│   ├── layouts/
│   │   └── app.view.php
│   ├── components/
│   │   ├── alert.view.php
│   │   └── button.view.php
│   ├── partials/
│   │   ├── header.view.php
│   │   └── footer.view.php
│   └── pages/
│       ├── home.view.php
│       └── about.view.php
└── cache/          (auto-created)

Advanced Usage

Custom Global Data

// Add data available to all templates
$templates->share('app_name', 'My Application');
$templates->share('current_user', $user);

// Or add multiple at once
$templates->shareMany([
    'app_name' => 'My Application',
    'version' => '1.0.0'
]);

Cache Management

// Clear all cached templates
$templates->clearCache();

// Get cache statistics
$stats = $templates->getCacheStats();
// Returns: ['enabled' => true, 'files' => 15, 'size' => 45231, 'size_formatted' => '44.17 KB']

Debug Mode

// Enable debug mode for verbose error reporting
$templates->setDebugMode(true);

// Get compilation information
$debug = $templates->getDebugInfo('welcome');

// Get compilation log
$log = $templates->getCompilationLog();

Template Validation

// Validate template syntax
$result = $templates->validateTemplate('welcome');

if (!$result['valid']) {
    foreach ($result['errors'] as $error) {
        echo "Error: {$error}\n";
    }
}

Error Handling

AnTemplate provides detailed error reporting:

use AnTemplate\AnTemplateException;

try {
    echo $templates->render('nonexistent');
} catch (AnTemplateException $e) {
    echo "Template Error: " . $e->getDetailedMessage();
    echo "Template: " . $e->getTemplateName();
    echo "File: " . $e->getTemplateFile();
    echo "Line: " . $e->getTemplateLine();
}

Performance

  • Template compilation caching - Templates are compiled once and cached
  • Optimized parsing - Efficient regex-based compilation
  • Minimal overhead - No external dependencies
  • Memory efficient - Smart buffering and cleanup

Requirements

  • PHP 8.0 or higher
  • No external dependencies

License

MIT License. See LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-10-27