PHPackages                             anunes/an-template - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. anunes/an-template

ActiveLibrary[Templating &amp; Views](/categories/templating)

anunes/an-template
==================

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

00PHP

Since Oct 27Pushed 6mo agoCompare

[ Source](https://github.com/anunes/an_tpl)[ Packagist](https://packagist.org/packages/anunes/an-template)[ RSS](/packages/anunes-an-template/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

AnTemplate
==========

[](#antemplate)

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

Features
--------

[](#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
------------

[](#installation)

Install via Composer:

```
composer require anunes/an-template

```

Quick Start
-----------

[](#quick-start)

### Basic Setup

[](#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

[](#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
---------------

[](#template-syntax)

### Variables

[](#variables)

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

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

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

```

### Conditionals

[](#conditionals)

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

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

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

@empty($posts)
    No posts found
@endempty

```

### Loops

[](#loops)

```
@foreach($users as $user)
    {{ $user->name }}
@endforeach

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

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

@while($condition)
    Processing...
@endwhile

```

### Template Inheritance

[](#template-inheritance)

**Layout (layouts/app.view.php):**

```

    @yield('title', 'Default Title')
    @stack('styles')

        @yield('header')

        @yield('content')

    @stack('scripts')

```

**Page template:**

```
@extends('layouts.app')

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

@section('content')
    Welcome to our site!
    Hello {{ $name }}!
@endsection

@push('styles')

@endpush

```

### Components

[](#components)

**Component (components/alert.view.php):**

```

    @if(isset($title))
        {{ $title }}
    @endif

        {{ $slot }}

```

**Using components:**

```

    Your profile has been updated.

{{-- Self-closing --}}

{{-- With named slots --}}

    @slot('header')
        Card Title
    @endslot

    This is the main card content.
@endcard

```

### Includes

[](#includes)

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

```

### Raw PHP

[](#raw-php)

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

Processing {{ $total }} items

```

### Stacks

[](#stacks)

```
@push('scripts')

@endpush

@push('scripts')

@endpush

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

```

Directory Structure
-------------------

[](#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
--------------

[](#advanced-usage)

### Custom Global Data

[](#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

[](#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

[](#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

[](#template-validation)

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

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

```

Error Handling
--------------

[](#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
-----------

[](#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
------------

[](#requirements)

- PHP 8.0 or higher
- No external dependencies

License
-------

[](#license)

MIT License. See LICENSE file for details.

Contributing
------------

[](#contributing)

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

###  Health Score

16

—

LowBetter than 5% of packages

Maintenance46

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/2c1795cbe83f8e779a98875a31748cb15d94044a63e399e87e4ced1b9076c2bd?d=identicon)[anunes](/maintainers/anunes)

---

Top Contributors

[![anunes](https://avatars.githubusercontent.com/u/1692570?v=4)](https://github.com/anunes "anunes (1 commits)")

### Embed Badge

![Health badge](/badges/anunes-an-template/health.svg)

```
[![Health](https://phpackages.com/badges/anunes-an-template/health.svg)](https://phpackages.com/packages/anunes-an-template)
```

###  Alternatives

[mustache/mustache

A Mustache implementation in PHP.

3.3k44.6M291](/packages/mustache-mustache)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[whitecube/nova-flexible-content

Flexible Content &amp; Repeater Fields for Laravel Nova.

8053.0M25](/packages/whitecube-nova-flexible-content)[mopa/bootstrap-bundle

Easy integration of twitters bootstrap into symfony2

7042.9M33](/packages/mopa-bootstrap-bundle)[limenius/react-bundle

Client and Server-side react rendering in a Symfony Bundle

3871.2M](/packages/limenius-react-bundle)[nicmart/string-template

StringTemplate is a very simple string template engine for php. I've written it to have a thing like sprintf, but with named and nested substutions.

2101.7M30](/packages/nicmart-string-template)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
