PHPackages                             luany/lte - 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. luany/lte

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

luany/lte
=========

LTE — AST-based template engine for PHP. Compiler-grade templating with zero regex parsing.

v1.0.2(1mo ago)052—0%1MITPHPPHP &gt;=8.2CI passing

Since Feb 25Pushed 1mo agoCompare

[ Source](https://github.com/luany-ecosystem/luany-lte)[ Packagist](https://packagist.org/packages/luany/lte)[ Docs](https://github.com/luany-ecosystem/luany-lte)[ RSS](/packages/luany-lte/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (4)Versions (9)Used By (1)

luany/lte
=========

[](#luanylte)

**AST-compiled template engine for PHP. Zero regex. Compiler-grade templating.**

**Version**: v1.0.0 | **PHP**: &gt;= 8.2 | **License**: MIT **Author**: António Ambrósio Ngola | **Org**: [luany-ecosystem](https://github.com/luany-ecosystem)

---

Table of Contents
-----------------

[](#table-of-contents)

1. [Overview](#1-overview)
2. [Installation](#2-installation)
3. [Basic Usage](#3-basic-usage)
4. [Output](#4-output)
5. [Conditionals](#5-conditionals)
6. [Loops](#6-loops)
7. [Layout System](#7-layout-system)
8. [Includes](#8-includes)
9. [Components &amp; Slots](#9-components--slots)
10. [Asset Directives](#10-asset-directives)
11. [Stack Directives](#11-stack-directives)
12. [PHP Blocks](#12-php-blocks)
13. [Security Directives](#13-security-directives)
14. [Auth Guards](#14-auth-guards)
15. [Debug Helpers](#15-debug-helpers)
16. [JSON Output](#16-json-output)
17. [Conditional Classes](#17-conditional-classes)
18. [Custom Directives](#18-custom-directives)
19. [Error Reporting](#19-error-reporting)
20. [Changelog](#20-changelog)

---

1. Overview
-----------

[](#1-overview)

LTE (Luany Template Engine) compiles `.lte` templates to PHP via a hand-written AST parser. There is **no regex** in the parsing pipeline — every token is identified character-by-character.

**Render pipeline:**

```
.lte source -> Parser (AST) -> Compiler (PHP string) -> cache file -> evaluate -> HTML

```

- `Parser` — tokenises source into AST nodes: `text`, `echo`, `raw_echo`, `php_block`, `directive`
- `Compiler` — translates AST nodes to PHP code strings
- `Engine` — orchestrates compile, cache, evaluate, resolves layouts and components

---

2. Installation
---------------

[](#2-installation)

```
composer require luany/lte
```

---

3. Basic Usage
--------------

[](#3-basic-usage)

```
use Luany\Lte\Engine;

$engine = new Engine(
    viewsPath:  '/path/to/views',
    cachePath:  '/path/to/storage/cache/views',
    autoReload: true,  // true = recompile every request (dev); false = use cache (production)
);

$html = $engine->render('pages.home', ['title' => 'Welcome', 'user' => $user]);
```

View files use the `.lte` extension and are resolved with dot notation: `'pages.home'` resolves to `views/pages/home.lte`

---

4. Output
---------

[](#4-output)

```
{{-- HTML-escaped output --}}
{{ $name }}
{{ $user->email }}
{{ strtoupper($text) }}

{{-- Raw/unescaped output --}}
{!! $trustedHtml !!}

{{-- Comments are removed from compiled output --}} {{-- This will not appear in
the HTML --}}
```

---

5. Conditionals
---------------

[](#5-conditionals)

```
@if($user)
Hello, {{ $user->name }}
@elseif($guest)
Welcome, guest
@else
Please login
@endif @unless($banned)
Welcome!
@endunless @isset($title)
{{ $title }}
@endisset @ifempty($items)
No items found.
@endifempty
```

---

6. Loops
--------

[](#6-loops)

```
@foreach($users as $user)
{{ $user->name }}
@endforeach @forelse($posts as $post)
{{ $post->title }}
@empty
No posts yet.
@endforelse {{-- Nested @forelse uses unique internal variables per level --}}
@forelse($categories as $category) @forelse($category->posts as $post)
{{ $post->title }}
@empty
No posts in {{ $category->name }}
@endforelse @empty
No categories.
@endforelse @for($i = 0; $i

    @yield('title', 'My App')
    @stack('head') @styles

    @yield('content') @scripts @stack('scripts')

```

**Page** (`views/pages/home.lte`):

```
@extends('layouts.main') @section('title', 'Home Page') @push('head')

@endpush @section('content')
Welcome
{{ $message }}
@endsection
```

DirectiveDescription`@extends('layout')`Declare the parent layout`@section('name') ... @endsection`Define a block section`@section('name', 'value')`Define an inline section`@yield('name')`Output a section`@yield('name', 'default')`Output a section with fallback`@stop`Alias for `@endsection`---

8. Includes
-----------

[](#8-includes)

```
{{-- Parent variables are passed automatically --}}
@include('components.navbar') {{-- With extra data merged in --}}
@include('components.card', ['title' => 'Hello', 'body' => $content])
```

---

9. Components &amp; Slots
-------------------------

[](#9-components--slots)

Components are reusable view fragments with named slots. The component view receives all slots as PHP variables.

**Component file** (`views/components/alert.lte`):

```

  @isset($title)
  {!! $title !!}
  @endisset {!! $slot !!}

```

**Usage in a parent view:**

```
@component('components.alert', ['type' => 'error']) @slot('title') Something
went wrong @endslot Please check your input and try again. @endcomponent
```

VariableSource`$slot`Default slot — content inside `@component...@endcomponent` not in a named `@slot``$title`Named slot — content of `@slot('title')...@endslot``$type`Explicit data — second argument to `@component`**Important:** Slot content is already-rendered HTML. Always use `{!! $slot !!}` and `{!! $namedSlot !!}` inside component views to avoid double-escaping.

Nested components are fully supported.

---

10. Asset Directives
--------------------

[](#10-asset-directives)

Inline `` and `` blocks declared anywhere in the view tree are collected and rendered at a designated position in the layout. Duplicate blocks (same content) are automatically deduplicated.

```
@style .card { padding: 1rem; border-radius: 4px; } @endstyle @script(defer)
document.querySelector('.card').addEventListener('click', fn); @endscript
```

In your layout:

```

  @styles

  ... @scripts

```

`@script(defer)` adds the `defer` attribute to the rendered `` tag.

---

11. Stack Directives
--------------------

[](#11-stack-directives)

Named stacks accumulate content from multiple `@push` calls. Unlike `@section`, pushes never replace previous content — they always append.

```
{{-- In any view or component --}} @push('head')

@endpush {{-- In layout --}} @stack('head')
```

---

12. PHP Blocks
--------------

[](#12-php-blocks)

```
{{-- Inline (self-closing) --}} @php($count = count($items)) {{-- Block --}}
@php $grouped = []; foreach ($items as $item) { $grouped[$item->category][] =
$item; } @endphp
```

Content inside `@php ... @endphp` is never parsed for LTE directives or echo tags.

---

13. Security Directives
-----------------------

[](#13-security-directives)

```
@csrf @method('PUT') ...
```

- `@csrf` — generates `` using `$_SESSION['csrf_token']` (auto-generated with `random_bytes(32)` if absent)
- `@method('PUT')` — generates `` for HTML form method override

---

14. Auth Guards
---------------

[](#14-auth-guards)

```
@auth
Welcome, {{ $_SESSION['user_name'] }}
@endauth @guest
Login
@endguest
```

Guards check `isset($_SESSION['user_id'])`. For custom auth logic, use `@if` or register a custom directive.

---

15. Debug Helpers
-----------------

[](#15-debug-helpers)

```
@dump($variable) {{-- var_dump() --}} @dd($variable) {{-- var_dump() + die --}}
```

---

16. JSON Output
---------------

[](#16-json-output)

Safe JSON output for use in JavaScript contexts. Always applies XSS-safe encoding flags.

```

  const config = @json($config);
  const users  = @json($users);

{{-- With additional flags (OR-ed with safe defaults) --}}

  const data = @json($data, JSON_PRETTY_PRINT);

```

Always applied: `JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE`. `` are encoded as `\u003C` / `\u003E`, preventing XSS injection.

---

17. Conditional Classes
-----------------------

[](#17-conditional-classes)

Builds a `class="..."` HTML attribute from a conditional array. Integer-keyed entries are always included; string-keyed entries are included only when their value is truthy.

```
 $isPrimary, 'btn-disabled' => !$active])>
    Click me

```

Given `$isPrimary = true`, `$active = true`:

```

```

Given `$isPrimary = false`, `$active = false`:

```

```

Using `ClassHelper` directly in PHP:

```
use Luany\Lte\ClassHelper;

// Compile to class string only
$classes = ClassHelper::compile(['flex', 'items-center', 'text-red-500' => $hasError]);
// -> 'flex items-center text-red-500'  (when $hasError = true)

// Compile to full class="..." attribute
$attr = ClassHelper::attr(['btn', 'active' => $isActive]);
// -> 'class="btn active"'
```

---

18. Custom Directives
---------------------

[](#18-custom-directives)

```
// Register before rendering (e.g. in a ServiceProvider boot method)
$engine->getCompiler()->directive('datetime', function (?string $args) {
    $format = $args ?: "'Y-m-d H:i'";
    return "";
});

$engine->getCompiler()->directive('money', function (?string $args) {
    return "";
});
```

Usage:

```
Posted: @datetime('d/m/Y H:i')
Price: @money($product->price)
```

The handler receives the raw argument string (content inside the parentheses) and must return a valid PHP string.

---

19. Error Reporting
-------------------

[](#19-error-reporting)

**Compilation errors** include the view name and source line:

```
LTE compilation error in view [pages.home]: Unclosed echo tag on line 12.

```

**Runtime errors** include the `.lte` source line number:

```
LTE render error in [pages.home.lte line 23]: Call to undefined method User::missing()

```

The Engine embeds `@lte:{N}` markers in compiled cache files and maps PHP runtime exceptions back to their original `.lte` source line.

---

20. Changelog
-------------

[](#20-changelog)

### next/v1 — Phase 5: Completion

[](#nextv1--phase-5-completion)

**New — `src/ComponentStack.php`**

- Stack-based context manager for `@component` / `@slot` / `@endslot` / `@endcomponent`
- Supports nested components via frame stack
- `isActive(): bool` — guards Engine reset during component rendering

**New — `src/ClassHelper.php`**

- `compile(array $classes): string` — conditional class array to space-separated string
- `attr(array $classes): string` — returns full `class="..."` attribute string

**Modified — `src/Parser.php`**

- Every AST node now carries `'line' => N` (1-based source line)
- Error messages include source line number
- Line counter maintained accurately across all token types

**Modified — `src/Compiler.php`**

- `@json($data)` / `@json($data, FLAGS)` — XSS-safe JSON output
- `@class([...])` — conditional CSS class builder via `ClassHelper::attr()`
- `@component` / `@slot` / `@endslot` / `@endcomponent` — component system
- Every compiled node prefixed with `` line marker

**Modified — `src/Engine.php`**

- `ComponentStack::reset()` called at root render start, guarded by `isActive()`
- Compilation errors wrapped with view name context
- `evaluate()` uses `ob_get_level()` guard for clean buffer restoration
- `resolveLteLine()` maps PHP exception line back to `.lte` source line

**Tests added:** `Phase5CompilerTest` (30), `Phase5EngineTest` (21), `ComponentStackTest` (11)

**Total: 170 tests, 252 assertions — all green, zero warnings.**

---

### v0.2.x baseline

[](#v02x-baseline)

AST parser, Compiler with built-in directives, Engine with layout/cache/include system, SectionStack, AssetStack.

Built-in directives: `@if`, `@elseif`, `@else`, `@endif`, `@unless`, `@endunless`, `@foreach`, `@endforeach`, `@for`, `@endfor`, `@while`, `@endwhile`, `@forelse`, `@empty`, `@endforelse`, `@php`, `@endphp`, `@csrf`, `@method`, `@auth`, `@endauth`, `@guest`, `@endguest`, `@extends`, `@section`, `@endsection`, `@stop`, `@yield`, `@include`, `@style`, `@endstyle`, `@script`, `@endscript`, `@styles`, `@scripts`, `@push`, `@endpush`, `@stack`, `@dump`, `@dd`, `@isset`, `@endisset`, `@ifempty`, `@endifempty`.

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance89

Actively maintained with recent releases

Popularity12

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 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.

###  Release Activity

Cadence

Every ~4 days

Total

7

Last Release

55d ago

Major Versions

v0.2.2 → v1.0.02026-03-23

PHP version history (2 changes)v0.1.0PHP &gt;=8.1

v1.0.0PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/9842ff34f898f8b92c95715d56ae48a2162eca040543183fc264391c554013ef?d=identicon)[Ngola-Programador-Full-Stack](/maintainers/Ngola-Programador-Full-Stack)

---

Top Contributors

[![antoniongoladev-design](https://avatars.githubusercontent.com/u/264429300?v=4)](https://github.com/antoniongoladev-design "antoniongoladev-design (20 commits)")

---

Tags

phptemplatecompilerastenginelteluany

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/luany-lte/health.svg)

```
[![Health](https://phpackages.com/badges/luany-lte/health.svg)](https://phpackages.com/packages/luany-lte)
```

###  Alternatives

[phug/phug

Pug (ex-Jade) facade engine for PHP, HTML template engine structured by indentation

67292.2k13](/packages/phug-phug)

PHPackages © 2026

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