PHPackages                             monkeyscloud/monkeyslegion-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. monkeyscloud/monkeyslegion-template

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

monkeyscloud/monkeyslegion-template
===================================

MLView – the MonkeysLegion template engine with components, slots, and caching

2.0.7(2mo ago)12.5k↓10.1%7MITPHPPHP ^8.4

Since Jul 23Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/MonkeysCloud/MonkeysLegion-Template)[ Packagist](https://packagist.org/packages/monkeyscloud/monkeyslegion-template)[ RSS](/packages/monkeyscloud-monkeyslegion-template/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (1)Dependencies (11)Versions (27)Used By (7)

MLView Template Engine
======================

[](#mlview-template-engine)

**MLView** is the built‑in, high‑performance template engine for **MonkeysLegion**, designed for clean, component‑driven views with minimal boilerplate. Inspired by Blade, Twig, Jinja2, and Phoenix LiveView — with multi-tier caching and 0.015 ms/render performance.

```
monkeyscloud/monkeyslegion-template v2.0
PHP 8.4+ | MIT License
476 tests | 902 assertions | PHPStan Level 8

```

---

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

[](#table-of-contents)

1. [Installation](#installation)
2. [Quick Start](#quick-start)
3. [Output &amp; Echoes](#output--echoes)
4. [Filters (Pipe Syntax)](#filters-pipe-syntax)
5. [Control Structures](#control-structures)
6. [Loops &amp; The `$loop` Variable](#loops--the-loop-variable)
7. [Components &amp; Slots](#components--slots)
8. [Layout Inheritance](#layout-inheritance)
9. [Stacks &amp; Asset Management](#stacks--asset-management)
10. [Template Inclusion](#template-inclusion)
11. [Frontend Helpers](#frontend-helpers)
12. [Form Helpers](#form-helpers)
13. [Framework Utilities](#framework-utilities)
14. [Advanced Directives](#advanced-directives)
15. [Fragment Caching](#fragment-caching)
16. [Template Macros](#template-macros)
17. [Element-Level Directives (HEEx-Style)](#element-level-directives-heex-style)
18. [Namespaces &amp; Theming](#namespaces--theming)
19. [View Composers &amp; Events](#view-composers--events)
20. [Streaming &amp; Async](#streaming--async)
21. [Security](#security)
22. [Caching Architecture](#caching-architecture)
23. [Performance](#performance)
24. [Testing](#testing)
25. [CLI Tooling](#cli-tooling)
26. [Extensibility](#extensibility)

---

Installation
------------

[](#installation)

```
composer require monkeyscloud/monkeyslegion-template
```

**Optional dependencies:**

PackagePurpose`psr/simple-cache`PSR-16 cache backend (Redis/Memcached)`monkeyscloud/monkeyslegion-cache`Full-featured caching with tags &amp; locks`monkeyscloud/monkeyslegion-di`Class-based component DI`monkeyscloud/monkeyslegion-cli`CLI commands (`view:compile`, `lint`)---

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

[](#quick-start)

### Directory Structure

[](#directory-structure)

```
my-app/
├─ resources/views/
│  ├─ home.ml.php              # Top-level view
│  ├─ posts/
│  │  └─ show.ml.php           # Nested: posts.show
│  ├─ layouts/
│  │  └─ app.ml.php            # Layout template
│  └─ components/
│     ├─ alert.ml.php          #  component
│     └─ card.ml.php           #  component
└─ var/cache/views/             # Compiled PHP (auto-generated)

```

### Hello World

[](#hello-world)

```
// resources/views/hello.ml.php
Hello, {{ $name }}!
```

```
use MonkeysLegion\Template\{Loader, Parser, Compiler, Renderer, MLView};

$loader   = new Loader('resources/views', 'var/cache/views');
$parser   = new Parser();
$compiler = new Compiler($parser);
$renderer = new Renderer($parser, $compiler, $loader, true, 'var/cache/views');

$view = new MLView($loader, $compiler, $renderer, 'var/cache/views');

echo $view->render('hello', ['name' => 'Alice']);
// Output: Hello, Alice!
```

First call: parse → compile → cache. Subsequent calls: include cached PHP directly.

**Dot-notation** resolves paths:

- `home` → `resources/views/home.ml.php`
- `posts.show` → `resources/views/posts/show.ml.php`

---

Output &amp; Echoes
-------------------

[](#output--echoes)

### Escaped Output

[](#escaped-output)

```
{{ $name }}                    {{-- HTML-escaped:  → &lt;script&gt; --}}
{{ $user->name }}              {{-- Object property --}}
{{ $count > 0 ? 'Yes' : 'No' }}  {{-- Expressions --}}
```

### Raw Output

[](#raw-output)

```
{!! $trustedHtml !!}           {{-- Unescaped — use responsibly --}}
```

### Comments

[](#comments)

```
{{-- This comment is removed from compiled output --}}
```

### PHP Blocks

[](#php-blocks)

```
@php
    $total = array_sum($prices);
@endphp
```

---

Filters (Pipe Syntax)
---------------------

[](#filters-pipe-syntax)

Inspired by Twig/Jinja2. Apply transformations via `|`:

```
{{ $name | upper }}                          {{-- ALICE --}}
{{ $name | lower | capitalize }}             {{-- Alice --}}
{{ $text | truncate(50, '...') }}            {{-- First 50 chars... --}}
{{ $price | number(2, '.', ',') }}           {{-- 1,234.56 --}}
{{ $items | pluck('name') | join(', ') }}    {{-- Item1, Item2, Item3 --}}
{{ $html | raw }}                            {{-- Skip escaping --}}
```

### Built-in Filters (35+)

[](#built-in-filters-35)

CategoryFilters**String**`upper`, `lower`, `capitalize`, `title`, `trim`, `length`, `reverse`, `repeat`, `replace`, `split`, `slug`, `nl2br`, `truncate`**Number**`number`, `abs`, `max`, `min`**Array**`join`, `first`, `last`, `count`, `sort`, `keys`, `values`, `unique`, `flatten`, `chunk`, `pluck`, `merge`**Date**`date` — works with `DateTime`, timestamps, and strings**Encoding**`json`, `e`, `escape`, `raw`**Utility**`default`, `prepend`, `append`, `wrap`, `pad`, `wordcount`, `excerpt`, `batch`, `map`, `filter`, `sum`, `avg`### Examples

[](#examples)

```
{{-- Date formatting --}}
{{ $createdAt | date('M d, Y') }}            {{-- Jan 15, 2026 --}}

{{-- Default values --}}
{{ $nickname | default('Anonymous') }}

{{-- Array manipulation --}}
{{ $users | pluck('email') | unique | count }}

{{-- Chaining --}}
{{ $bio | truncate(100) | nl2br }}

{{-- JSON output --}}
{{ $config | json }}
```

### Custom Filters

[](#custom-filters)

```
$view->addFilter('currency', fn($v) => '$' . number_format($v, 2));
// Usage: {{ $price | currency }}
```

---

Control Structures
------------------

[](#control-structures)

### Conditionals

[](#conditionals)

```
@if($user->isAdmin())
    Admin
@elseif($user->isModerator())
    Mod
@else
    User
@endif
```

### Conditional Sugar

[](#conditional-sugar)

```
@unless($isAdmin)
    You are not an admin.
@endunless

@isset($records)
    Found {{ count($records) }} records.
@endisset

@empty($results)
    No results found.
@endempty
```

### Switch

[](#switch)

```
@switch($status)
    @case('active')
        Active
    @break
    @case('pending')
        Pending
    @break
    @default
        Unknown
@endswitch
```

---

Loops &amp; The `$loop` Variable
--------------------------------

[](#loops--the-loop-variable)

### `@foreach`

[](#foreach)

Every `@foreach` provides a `$loop` variable with iteration metadata:

```
@foreach($users as $user)
    @if($loop->first)

    @endif

    {{ $loop->iteration }}. {{ $user->name }}

    @if($loop->last)

    @endif
@endforeach
```

**`$loop` properties:**

PropertyTypeDescription`$loop->index``int`Zero-based index`$loop->iteration``int`One-based index`$loop->remaining``int`Items remaining`$loop->count``int`Total items`$loop->first``bool`Is first iteration`$loop->last``bool`Is last iteration`$loop->even``bool`Is even iteration`$loop->odd``bool`Is odd iteration`$loop->depth``int`Nesting depth (1+)`$loop->parent``?Loop`Parent loop (nested)### `@forelse`

[](#forelse)

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

### `@for` / `@while`

[](#for--while)

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

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

### Loop Control

[](#loop-control)

```
@foreach($items as $item)
    @if($item->hidden)
        @continue
    @endif
    @if($loop->iteration > 5)
        @break
    @endif
    {{ $item->name }}
@endforeach
```

---

Components &amp; Slots
----------------------

[](#components--slots)

### Using Components

[](#using-components)

```
{{-- Simple component --}}

    Watch out!

{{-- Self-closing --}}

{{-- With named slots --}}

        Card Title

    Main content goes here.

        Save

```

### Creating Components

[](#creating-components)

```
{{-- resources/views/components/alert.ml.php --}}
@param(['type' => 'info', 'dismissible' => false])

    @if($slots->has('header'))
        {{ $slots->header }}
    @endif

    {{ $slot }}

    @if($dismissible)

    @endif

```

### Function Components

[](#function-components)

Lightweight, closure-based components — no template file needed:

```
$view->component('badge', fn(string $text, string $color = 'blue') =>
    "" . htmlspecialchars($text) . ""
);

// Usage:
```

### Attribute Bag

[](#attribute-bag)

All extra attributes are collected in `$attributes`:

```
{{-- Component template --}}
merge(['class' => 'card']) }}>
    {{ $slot }}

{{-- Usage --}}
Content
{{-- Output: Content --}}
```

### Component Data

[](#component-data)

Inside a component:

VariableDescription`$slot`Default slot content`$slots->name`Named slot content`$slots->has('name')`Check if named slot exists`$attributes`AttributeBag with all passed attributes`@aware(['key' => 'default'])`Access parent component data---

Layout Inheritance
------------------

[](#layout-inheritance)

### Parent Layout

[](#parent-layout)

```
{{-- resources/views/layouts/app.ml.php --}}
DOCTYPE html>

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

    @yield('nav')

        @yield('content')

    @stack('scripts')

```

### Child View

[](#child-view)

```
{{-- resources/views/home.ml.php --}}
@extends('layouts.app')

@section('title')
    Home Page
@endsection

@section('content')
    Welcome!
    This is the home page.
@endsection

@push('scripts')

@endpush
```

---

Stacks &amp; Asset Management
-----------------------------

[](#stacks--asset-management)

Push CSS/JS from any child view or component into named stacks in the layout:

```
{{-- In layout --}}

    @stack('styles')

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

{{-- In child view or component --}}
@push('scripts')

@endpush

@prepend('styles')

@endprepend

{{-- Push once (dedup) --}}
@pushOnce('scripts')

@endPushOnce
```

---

Template Inclusion
------------------

[](#template-inclusion)

```
{{-- Basic include --}}
@include('partials.header')

{{-- Include with data --}}
@include('partials.alert', ['type' => 'warning', 'message' => 'Heads up!'])

{{-- Conditional includes --}}
@includeWhen($isLoggedIn, 'nav.user-menu')
@includeUnless($isAdmin, 'nav.guest-menu')

{{-- Include first match --}}
@includeFirst(['custom.admin', 'admin.dashboard'], ['data' => $data])

{{-- Include if exists --}}
@includeIf('optional.sidebar')
```

---

Frontend Helpers
----------------

[](#frontend-helpers)

DirectiveExampleOutput`@json($data)``@json($config)`Safe JSON in HTML`@js($data)``@js($settings)`JS-safe (unescaped unicode)`@class([...])``@class(['btn', 'active' => $isActive])``class="btn active"``@style([...])``@style(['color: red' => $isError])``style="color: red"````
 $isPrimary, 'disabled' => !$enabled])>
    Submit

 $hasError, 'font-weight: bold' => $important])>
    Content

    const config = @json($appConfig);

```

---

Form Helpers
------------

[](#form-helpers)

```

    @csrf
    @method('PUT')

    isAdmin)>

        @foreach($roles as $role)

                {{ $role }}

        @endforeach

    @error('name')
        {{ $message }}
    @enderror

```

---

Framework Utilities
-------------------

[](#framework-utilities)

### Environment Checks

[](#environment-checks)

```
@env('production')
    {{-- Only in production --}}

@endenv

@production
    {{-- Shorthand for @env('production') --}}
@endproduction
```

### Authentication

[](#authentication)

```
@auth
    Welcome, {{ auth()->user()->name }}!
@endauth

@guest
    Login
@endguest
```

### Authorization

[](#authorization)

```
@can('edit', $post)
    Edit
@endcan

@cannot('delete', $post)
    Cannot delete
@endcannot
```

### Session

[](#session)

```
@session('success')
    {{ $value }}
@endsession
```

### Service Injection

[](#service-injection)

```
@inject('metrics', 'App\Services\MetricsService')

Monthly visits: {{ $metrics->getMonthlyVisits() }}
```

---

Advanced Directives
-------------------

[](#advanced-directives)

### HTMX Fragment Rendering

[](#htmx-fragment-rendering)

Render only a fragment for HTMX partial updates:

```

    @fragment('user-table')

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

    @endfragment

```

### Teleport

[](#teleport)

Move content to a different DOM location (like Vue's ``):

```
@teleport('#modals')
    Modal content
@endteleport
```

### Persist (HTMX)

[](#persist-htmx)

Mark elements that should persist across HTMX morph-merges:

```
@persist('audio-player')

@endpersist
```

### Model Type Hints (IDE Support)

[](#model-type-hints-ide-support)

```
@model(App\Entity\User)
{{-- IDE autocomplete now knows $model is a User --}}
{{ $model->name }}
```

### Once

[](#once)

```
@once

@endonce
```

### Verbatim

[](#verbatim)

Prevent MLView from parsing a block (useful for JS frameworks):

```
@verbatim

        {{ vueVariable }}

@endverbatim
```

### Autoescape

[](#autoescape)

Set the escaping context for a block:

```
@autoescape('js')
    var name = {{ $name }};
@endautoescape
```

---

Fragment Caching
----------------

[](#fragment-caching)

Cache expensive template fragments with PSR-16. Requires a cache backend.

```
{{-- Cache sidebar for 5 minutes --}}
@cache('sidebar-' . $userId, 300)

        @foreach($expensiveQuery as $item)
            {{ $item->name }}
        @endforeach

@endcache

{{-- Cache forever (no TTL) --}}
@cache('static-nav')
    ...
@endcache
```

**Setup:**

```
$view = new MLView($loader, $compiler, $renderer, $cacheDir, [
    'cache' => $redisCache, // Psr\SimpleCache\CacheInterface
]);
```

When no cache backend is configured, `@cache` blocks render normally with zero overhead.

---

Template Macros
---------------

[](#template-macros)

Define reusable template snippets:

```
{{-- Define a macro --}}
@macro('statusBadge', $status, $label)
    {{ $label }}
@endmacro

{{-- Use the macro --}}
@call('statusBadge', 'success', 'Active')
@call('statusBadge', 'danger', 'Inactive')
```

---

Element-Level Directives (HEEx-Style)
-------------------------------------

[](#element-level-directives-heex-style)

Inspired by Phoenix LiveView — attach directives directly to HTML elements:

```
{{-- Conditional rendering --}}
Welcome!

{{-- Negated conditional --}}
You are not authorized.

{{-- Loop rendering --}}
{{ $item->name }}
```

Compiles to standard PHP control structures wrapping the element.

---

Namespaces &amp; Theming
------------------------

[](#namespaces--theming)

### View Namespaces

[](#view-namespaces)

Organize views by package or module:

```
$view->addNamespace('ui', __DIR__ . '/vendor/ui-lib/views');

// Usage: ui::alert → /vendor/ui-lib/views/alert.ml.php
echo $view->render('ui::alert', ['type' => 'info']);
```

### Theming System

[](#theming-system)

```
// 1. Multiple view paths (checked in order)
$view->addViewPath('/path/to/overrides');

// 2. Theme activation (prepends theme path)
$view->setTheme('dark');
// Checks: themes/dark/home.ml.php → resources/views/home.ml.php

// 3. Namespace overrides in themes
// themes/dark/vendor/ui/alert.ml.php overrides ui::alert
```

---

View Composers &amp; Events
---------------------------

[](#view-composers--events)

### View Composers

[](#view-composers)

Automatically attach data to views by pattern:

```
// Attach $categories to all 'shop.*' views
$view->composer('shop.*', function (ViewData $data) {
    $data->set('categories', Category::all());
});

// Multiple patterns
$view->composer(['layouts.*', 'partials.nav'], function (ViewData $data) {
    $data->set('menuItems', Menu::forUser(auth()->user()));
});
```

### Shared Data

[](#shared-data)

```
$view->share('appName', 'MonkeysCloud');
// $appName available in ALL templates
```

### Lifecycle Events

[](#lifecycle-events)

```
// Before render
$view->rendering(function (ViewRendering $event) {
    // $event->name, $event->data
    $event->data['renderTime'] = microtime(true);
});

// After render
$view->rendered(function (ViewRendered $event) {
    // $event->name, $event->data, $event->output
    Log::info("Rendered {$event->name}");
});
```

---

Streaming &amp; Async
---------------------

[](#streaming--async)

Render templates as a stream of chunks for progressive HTML delivery:

```
$view = new MLView($loader, $compiler, $renderer, $cacheDir);

foreach ($view->stream('dashboard', $data) as $chunk) {
    echo $chunk;
    flush();
}
```

### Render String (No File)

[](#render-string-no-file)

```
$html = $view->renderString('Hello {{ $name }}!', ['name' => 'World']);
```

---

Security
--------

[](#security)

### Context-Aware Escaping

[](#context-aware-escaping)

```

    @escape('html', $text)

```

Contexts: `html`, `js`, `url`, `css`, `attr`

### Strict Mode

[](#strict-mode)

Warn on raw `{!! !!}` usage — useful for security audits:

```
$view = new MLView($loader, $compiler, $renderer, $cacheDir, [
    'strict_mode' => true,
]);
```

### Default Escaping

[](#default-escaping)

All `{{ }}` output is escaped via `htmlspecialchars()` with `ENT_QUOTES` and `UTF-8`. Use `{!! !!}` or the `| raw` filter only for trusted content.

---

Caching Architecture
--------------------

[](#caching-architecture)

MLView uses a 3-tier caching system:

```
┌─────────────────────────────────────────────────────┐
│  L1: In-Memory Pool (CompiledTemplatePool)          │
│  Per-request dedup — avoids filemtime on repeats    │
├─────────────────────────────────────────────────────┤
│  L2: View Cache (ViewCacheInterface)                │
│  FilesystemViewCache — atomic writes, OPcache-aware │
│  Psr16ViewCache — Redis/Memcached adapter           │
├─────────────────────────────────────────────────────┤
│  L3: Fragment Cache (@cache directive)              │
│  PSR-16 store for expensive template blocks         │
└─────────────────────────────────────────────────────┘

```

### Configuration

[](#configuration)

```
// Development (default) — checks filemtime, auto-recompiles
$view = new MLView($loader, $compiler, $renderer, $cacheDir);

// Production — skip filemtime checks, max speed
$view = new MLView($loader, $compiler, $renderer, $cacheDir, [
    'production' => true,
]);

// Full-featured — PSR-16 backend + fragment caching
$view = new MLView($loader, $compiler, $renderer, $cacheDir, [
    'production' => true,
    'cache'      => $redisCache, // Psr\SimpleCache\CacheInterface
]);
```

### Cache Adapters

[](#cache-adapters)

AdapterUse Case`FilesystemViewCache`Default. Atomic writes, OPcache invalidation, dependency tracking`Psr16ViewCache`Redis/Memcached via any PSR-16 implementationCustomImplement `ViewCacheInterface`### Cache Commands

[](#cache-commands)

```
# Clear all compiled templates
$view->clearCache();

# Or via CLI
./bin/mlview cache:clear
```

---

Performance
-----------

[](#performance)

### Benchmarks (PHP 8.5, Apple Silicon)

[](#benchmarks-php-85-apple-silicon)

OperationTimeNotesSimple render (1000×)**0.015 ms/render**L1 pool hitLoop render 100 items (500×)**0.038 ms/render**With `$loop` variableCompilation (1000×)**0.013 ms/compile**With early-exit optimizationFilter pipeline (1000×)**0.025 ms/render**Multiple chained filtersCache freshness check (10000×)**0.004 ms/check**filemtime comparisonLarge table (1000×10)**3.0 ms**342 KB outputProduction vs Dev mode**13.8× speedup**Skip filemtime checks### Optimizations Applied

[](#optimizations-applied)

- **Early-exit guards**: 40+ directive compilers skipped via `str_contains()` when not present
- **Cached FilterRegistry**: single instance shared across all expressions
- **Single-pass simple directives**: 11 no-arg directives compiled in one regex
- **L1 in-memory pool**: eliminates repeated filemtime calls within same request
- **Atomic writes**: `file_put_contents()` with `LOCK_EX` for safe concurrent access
- **OPcache integration**: `opcache_invalidate()` on recompile for immediate effect

---

Testing
-------

[](#testing)

### Test Utilities

[](#test-utilities)

```
use MonkeysLegion\Template\Testing\TestView;

$result = $view->test('dashboard', ['user' => $user]);

$result->assertSee('Welcome');
$result->assertDontSee('Error');
$result->assertSeeInOrder(['Header', 'Content', 'Footer']);
```

### Running Tests

[](#running-tests)

```
composer test                 # All 476 tests
composer test:unit           # Unit tests only
composer test:integration    # Integration tests only
composer test:perf           # Performance benchmarks
composer phpstan             # Static analysis (Level 8)
composer check               # CS + PHPStan + Tests
```

---

CLI Tooling
-----------

[](#cli-tooling)

### Template Linting

[](#template-linting)

```
# Lint the default views directory
./bin/mlview lint resources/views

# Check multiple paths
./bin/mlview lint resources/views,modules/blog/views
```

Checks for:

- Missing components (``)
- Missing included views (`@include`)
- Syntax errors
- Unclosed directives

Non-zero exit code on errors — CI/CD ready.

### Pre-compilation

[](#pre-compilation)

```
# Compile all templates ahead of time (deploy step)
./bin/mlview view:compile resources/views
```

---

Extensibility
-------------

[](#extensibility)

### Custom Directives

[](#custom-directives)

```
$view->addDirective('datetime', function ($expression) {
    return "";
});
// Usage: @datetime($timestamp)
```

### Custom Filters

[](#custom-filters-1)

```
$view->addFilter('initials', function (string $name): string {
    return implode('', array_map(fn($w) => strtoupper($w[0]), explode(' ', $name)));
});
// Usage: {{ $fullName | initials }}  →  "JD"
```

### Custom Cache Adapter

[](#custom-cache-adapter)

```
use MonkeysLegion\Template\Cache\ViewCacheInterface;

class MyCache implements ViewCacheInterface
{
    public function isFresh(string $name, string $sourcePath, string $compiledPath): bool { /* ... */ }
    public function put(string $compiledPath, string $compiledPhp): void { /* ... */ }
    public function getCompiledPath(string $name, string $sourcePath): string { /* ... */ }
    public function forget(string $name): void { /* ... */ }
    public function flush(): void { /* ... */ }
}

$renderer->setViewCache(new MyCache());
```

### Pipeline Extension Points

[](#pipeline-extension-points)

ExtensionHowCustom directives`$view->addDirective()`Custom filters`$view->addFilter()`Function components`$view->component()`Custom cacheImplement `ViewCacheInterface`Custom loaderImplement `LoaderInterface`View composers`$view->composer()`Render events`$view->rendering()` / `$view->rendered()`---

Complete Directive Reference
----------------------------

[](#complete-directive-reference)

### Output

[](#output)

SyntaxDescription`{{ $var }}`Escaped output`{!! $var !!}`Raw output`{{ $var | filter }}`Filtered output`{{-- comment --}}`Template comment (stripped)### Control Flow

[](#control-flow)

DirectiveDescription`@if` / `@elseif` / `@else` / `@endif`Conditionals`@unless` / `@endunless`Negated if`@isset` / `@endisset`Variable existence check`@empty` / `@endempty`Empty check`@switch` / `@case` / `@default` / `@endswitch`Switch`@foreach` / `@endforeach`Loop with `$loop` variable`@forelse` / `@empty` / `@endforelse`Loop with empty fallback`@for` / `@endfor`C-style for loop`@while` / `@endwhile`While loop`@break` / `@continue`Loop control### Components &amp; Layout

[](#components--layout)

DirectiveDescription`` / ``Component usage``Named slot`@slot('name')` / `@endslot`Slot (alternative syntax)`@param([...])`Component defaults`@aware([...])`Parent component data`@extends('layout')`Layout inheritance`@section('name')` / `@endsection`Section definition`@yield('name', 'default')`Section output`@parent`Insert parent section content### Template Composition

[](#template-composition)

DirectiveDescription`@include('view', [...])`Include template`@includeIf('view')`Include if exists`@includeWhen($cond, 'view')`Conditional include`@includeUnless($cond, 'view')`Negated conditional include`@includeFirst(['a', 'b'])`First available`@inject('var', 'Class')`Service injection### Stacks

[](#stacks)

DirectiveDescription`@stack('name')`Output stack`@push('name')` / `@endpush`Append to stack`@prepend('name')` / `@endprepend`Prepend to stack`@pushOnce('name')` / `@endPushOnce`Deduplicated push### Frontend

[](#frontend)

DirectiveDescription`@json($data)`JSON encode`@js($data)`JS-safe encode`@class([...])`Conditional CSS classes`@style([...])`Conditional inline styles`@checked($cond)`Checked attribute`@selected($cond)`Selected attribute`@disabled($cond)`Disabled attribute`@readonly($cond)`Readonly attribute`@required`Required attribute### Forms &amp; Security

[](#forms--security)

DirectiveDescription`@csrf`CSRF token field`@method('PUT')`HTTP method spoofing`@error('field')` / `@enderror`Validation errors`@old('field', 'default')`Old input value`@escape('context', $var)`Context-aware escaping### Framework

[](#framework)

DirectiveDescription`@env('name')` / `@endenv`Environment check`@production` / `@endproduction`Production shorthand`@auth` / `@endauth`Authenticated check`@guest` / `@endguest`Guest check`@can('ability', $model)` / `@endcan`Authorization`@cannot('ability', $model)` / `@endcannot`Authorization negated`@session('key')` / `@endsession`Session check`@hasSection('name')`Check section exists`@sectionMissing('name')`Check section missing### Advanced

[](#advanced)

DirectiveDescription`@cache('key', ttl)` / `@endcache`Fragment caching`@macro('name', ...)` / `@endmacro`Define macro`@call('name', ...)`Invoke macro`@fragment('name')` / `@endfragment`HTMX partial rendering`@teleport('selector')` / `@endteleport`Content teleport`@persist('id')` / `@endpersist`HTMX persist`@model(Class)`IDE type hint`@autoescape('context')` / `@endautoescape`Block escaping`@options([...])`Template options`@once` / `@endonce`Render once`@verbatim` / `@endverbatim`Skip parsing`@php` / `@endphp`Raw PHP block`@use('Class')`Import class### Element-Level (HEEx-Style)

[](#element-level-heex-style)

AttributeDescription`:if="$condition"`Conditional element`:unless="$condition"`Negated conditional`:for="$items as $item"`Loop element### Debugging

[](#debugging)

DirectiveDescription`@dump($var)`Formatted var\_dump`@dd($var)`Dump and die---

License
-------

[](#license)

MIT © MonkeysCloud

###  Health Score

51

—

FairBetter than 95% of packages

Maintenance88

Actively maintained with recent releases

Popularity23

Limited adoption so far

Community20

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 78% 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 ~13 days

Recently: every ~1 days

Total

22

Last Release

61d ago

Major Versions

1.0.11 → 2.0.0.x-dev2026-04-15

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2913369?v=4)[Jorge Peraza](/maintainers/yorchperaza)[@yorchperaza](https://github.com/yorchperaza)

---

Top Contributors

[![yorchperaza](https://avatars.githubusercontent.com/u/2913369?v=4)](https://github.com/yorchperaza "yorchperaza (46 commits)")[![Amanar-Marouane](https://avatars.githubusercontent.com/u/155680356?v=4)](https://github.com/Amanar-Marouane "Amanar-Marouane (11 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (2 commits)")

---

Tags

frameworkphpphp8template

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/monkeyscloud-monkeyslegion-template/health.svg)

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

###  Alternatives

[limenius/react-bundle

Client and Server-side react rendering in a Symfony Bundle

3851.2M](/packages/limenius-react-bundle)[area17/laravel-auto-head-tags

Laravel Auto Head Tags helps you build the list of head elements for your app

4616.1k](/packages/area17-laravel-auto-head-tags)[jelix/wikirenderer

WikiRenderer is a library to generate HTML or anything else from wiki content.

1712.3k1](/packages/jelix-wikirenderer)[webkinder/sproutset

A Composer package for handling responsive images in Roots Bedrock + Sage + Blade projects.

282.2k](/packages/webkinder-sproutset)

PHPackages © 2026

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