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

1.0.10(2mo ago)01.3k↑250%4MITPHPPHP ^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 1mo ago

READMEChangelog (1)Dependencies (6)Versions (14)Used By (4)

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

[](#mlview-template-engine)

MLView is the built‑in, lightweight template engine for **MonkeysLegion**, designed to help you write clean, component‑driven views with minimal boilerplate.

---

🌟 Key Features
--------------

[](#-key-features)

- **Escaped output**: `{{ $var }}` → safe, HTML‑escaped data
- **Raw output**: `{!! $html !!}` → unescaped HTML (use responsibly)
- **Logic**: `@if`, `@foreach` with `$loop` variable, `@switch`, `@unless`, `@isset`, `@empty`
- **Stacks**: `@stack`, `@push`, `@prepend` for efficient asset management
- **Encryption**: `@inject` for service injection
- **Components**: `...` → reusable view fragments
- **Slots**: `@slot('header')…@endslot` → named content areas inside components
- **Layout inheritance**: `@extends('parent')`, `@section('name')…@endsection`, `@yield('name')`
- **Caching &amp; Hot‑Reload**: compiled PHP cached in `var/cache/views`; auto‑recompiles modified templates

---

📂 Directory Structure
---------------------

[](#-directory-structure)

```
my-app/
├─ resources/views/
│  ├─ home.ml.php              # Top‑level view
│  ├─ posts/
│  │  └─ show.ml.php           # Nested view under posts/
│  └─ components/
│     ├─ layout.ml.php         # Layout component for
│     └─ alert.ml.php          # Alert component
└─ var/
   └─ cache/views/             # Generated PHP cache files

```

**Dot‑notation** when rendering:

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

---

2 · Hello, World
----------------

[](#2--hello-world)

Hello, {{ $name }}!
===================

[](#hello--name-)

use MonkeysLegion\\Template\\MLView;

$view = new MLView(base\_path('resources/views'));

echo $view-&gt;render('hello', \['name' =&gt; 'Alice'\]);

The first call parses → compiles → caches the template; subsequent renders are just an include.

---

3 · Component Syntax
--------------------

[](#3--component-syntax)

 Welcome, {{ $user-&gt;name }} Your last login was {{ $user-&gt;lastLogin-&gt;diffForHumans() }}.

 ↔ PHP class App\\View\\Components\\Component.

x-slot:name fills the component's $this-&gt;slot('name').

{{ … }} escapes htmlspecialchars(); {!! … !!} prints raw.

---

6 · Directives &amp; Helpers
----------------------------

[](#6--directives--helpers)

MLView supports a wide range of directives to make your templates expressive.

### Control Structures

[](#control-structures)

DirectiveDescription`@if` / `@elseif` / `@else`Standard conditional blocks`@unless($cond)`Equivalent to `@if(!$cond)``@isset($var)` / `@empty($var)`Check if variable is set or empty`@switch` / `@case` / `@default`Switch statements`@foreach` / `@for` / `@while`Loops (`$loop` available in `@foreach`)`@break` / `@continue`Loop control### Frontend Helpers

[](#frontend-helpers)

DirectiveDescription`@json($data)`Outputs safe JSON encoded data`@js($data)`Outputs JavaScript-safe data (unescaped unicode)`@class(['btn', 'active' => $isActive])`Conditionally compiled class string`@style(['color: red' => $isError])`Conditionally compiled inline styles`@checked($cond)`Outputs `checked` attribute if true`@selected($cond)`Outputs `selected` attribute if true`@disabled($cond)`Outputs `disabled` attribute if true`@readonly($cond)`Outputs `readonly` attribute if true### Framework Utilities

[](#framework-utilities)

DirectiveDescription`@csrf`Outputs CSRF token field (hidden input)`@method('PUT')`Outputs method spoofing field (hidden input)`@error('field')`Checks for validation errors (`@enderror` to close)`@old('field', 'default')`Retrieves old input value`@lang('key', ['replace'])`Translates a string`@env('production')`Checks application environment`@auth` / `@guest`Checks authentication status### Miscellaneous

[](#miscellaneous)

DirectiveDescription`@once`Ensures content is only rendered once per request`@verbatim`Proteced block (prevents parsing of `{{ }}`)`@php`Execute raw PHP code block---

🛠️ Component Best Practices
---------------------------

[](#️-component-best-practices)

### Simple Component Creation

[](#simple-component-creation)

Components should be straightforward with minimal PHP boilerplate:

```

```

- **Check slots**: Always use `isset($slots['name'])` before accessing slots
- **Access slot content**: Use `$slots['header']()` for named slots or `$slotContent` for default content
- **Component attributes**: All attributes passed to your component are available as PHP variables

### Advanced Component Rendering

[](#advanced-component-rendering)

Behind the scenes, MLView uses a component rendering pipeline:

1. Slots are processed recursively to handle nested components
2. Component attributes are extracted into the local scope
3. The main content is captured in `$slotContent`
4. Component output is inserted into the parent template

This approach allows for reusable components that maintain proper scoping while keeping them simple.

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

@section('title')
  {{ \$title }}
@endsection

@section('header')
  Welcome!
@endsection

@section('content')
  Home page content…
@endsection
```

- `@extends('layouts.app')` indicates the parent template
- `@section('…')…@endsection` blocks define content
- `@yield('…')` in the parent is replaced by each section

⚙️ Rendering Pipeline
---------------------

[](#️-rendering-pipeline)

1. **Loader**: resolves raw `.ml.php` + cache path
2. **Parser**: transforms ``, `@slot`, `@section`, `@yield`, `{{ }}`, `{!! !!}` into an AST
3. **Compiler**: generates pure PHP code from the AST
4. **Cache**: writes to `var/cache/views/.php` and `include`s it

---

🔄 Caching &amp; Hot‑Reload
--------------------------

[](#-caching--hotreload)

- **Location**: `var/cache/views`
- **Auto‑invalidate**: template timestamp checked on each render
- **Manual clear**: `php vendor/bin/ml cache:clear`

---

🔧 Extensibility
---------------

[](#-extensibility)

- **Custom directives**: add regex callbacks in `Compiler`
- **AST extensions**: enhance `Parser` for new syntax
- **Alternative loaders**: swap `Loader` for custom sources (DB, remote)

---

Debugging
---------

[](#debugging)

- **Dump data**: `@dump(\$variable)` inside templates to var\_dump

Happy templating with MLView! 🚀

MLView Component System
=======================

[](#mlview-component-system)

The MLView template engine supports a component system to build reusable UI elements.

Component Usage
---------------

[](#component-usage)

Use components in your templates with `` tags:

```

    This is a warning message!

    @slot('header')
        Card Title
    @endslot

    This is the main content (default slot)

    @slot('footer')
        Action
    @endslot

```

Creating Components
-------------------

[](#creating-components)

Components should use PHP syntax for optimal compatibility:

```

@param(['type' => 'info', 'dismissible' => false])

```

### Component Parameters

[](#component-parameters)

Components can define default parameters using the `@param` directive:

```
@param(['name' => 'default value', 'another' => true, 'count' => 5])
```

These parameters:

- Must be defined at the top of the component file
- Will be available as PHP variables inside the component
- Can be overridden by passing attributes to the component

When using the component:

```

This is an info message

This is a danger alert!

This is dismissible
```

The parameters system allows component authors to define sensible defaults while giving component users the flexibility to customize as needed.

Slot Handling
-------------

[](#slot-handling)

Define slots using Blade-style `@slot` directives:

```

    @slot('header')
        Card Title
    @endslot

    Default content

```

Component Data
--------------

[](#component-data)

Inside a component:

- `$slotContent` contains the default (unnamed) slot content
- `$slots['name']()` calls and renders named slots
- `$attributes` object (AttributeBag) contains all passed attributes
- `@aware(['color' => 'gray'])` directives to access parent component data

### Attribute Bag

[](#attribute-bag)

You can output all attributes passed to a component using the `$attributes` variable:

```
merge(['class' => 'alert alert-info']) }}>
    {{ $slot }}

```

This allows usages like: ``, where `class` merges with the default and `id` is added.

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

[](#template-inclusion)

### @include directive

[](#include-directive)

The `@include` directive lets you include one template from another:

```

@include('partials.header')

@include('partials.alert', ['type' => 'warning', 'message' => 'Danger ahead!'])
```

Templates included with `@include` should be placed in the standard views directory structure and are referenced using dot notation:

- `@include('header')` → `resources/views/header.ml.php`
- `@include('partials.header')` → `resources/views/partials/header.ml.php`

### Component vs @include

[](#component-vs-include)

- **Components** (``) are placed in `resources/views/components/name.ml.php`
- **Included templates** (`@include`) can be placed anywhere in the views directory
- Components support slots and have a dedicated lifecycle
- Included templates are simply merged into the parent template

---

7 · Stacks &amp; Layouts
------------------------

[](#7--stacks--layouts)

Push content to named stacks from anywhere in your view hierarchy, perfect for injecting scripts or styles from child views.

```

    @stack('styles')

    @stack('scripts')

@push('scripts')

@endpush

@prepend('styles')
    body { background: #333; }
@endprepend
```

---

8 · Service Injection
---------------------

[](#8--service-injection)

Inject services directly into your templates using `@inject`:

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

    Monthly Visits: {{ $metrics->getMonthlyVisits() }}

```

---

9 · The Loop Variable
---------------------

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

Inside `@foreach` loops, a `$loop` variable is automatically available to track iteration state:

```
@foreach($users as $user)
    @if($loop->first)
        Start of list
    @endif

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

    @if($loop->last)
        End of list
    @endif
@endforeach
```

Properties available: `index`, `iteration`, `remaining`, `count`, `first`, `last`, `even`, `odd`, `depth`, `parent`.

---

10 · Conditional Sugar
----------------------

[](#10--conditional-sugar)

Use shorthand directives for clearer intent:

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

@isset($records)
    // $records is defined and not null
@endisset

@empty($records)
    // $records is empty
@endempty

@switch($i)
    @case(1)
        First case...
    @break
    @default
        Default case...
@endswitch
```

---

11 · Advanced Includes
----------------------

[](#11--advanced-includes)

Conditionally include views to keep templates clean:

```
@includeWhen($isLoggedIn, 'nav.user-menu')
@includeUnless($isAdmin, 'nav.guest-menu')
@includeFirst(['custom.admin', 'admin.dashboard'], ['data' => $data])
```

---

@endverbatim

```

---

## 13 · Security & Extensibility

### Context-Aware Escaping (`@escape`)

MLView provides context-aware escaping to prevent XSS in various contexts (HTML, Attributes, JS, URL, CSS).
By default, `{{ $var }}` escapes for HTML body.

Use `@escape` for specific contexts:

```php

    @escape('html', $text)

```

### Strict Mode

[](#strict-mode)

Enable strict mode to warn about raw output `{!! !!}` usage, which helps identify potential security risks.

```
$view = new MLView($path, ['strict_mode' => true]);
```

When enabled, any `{!! $var !!}` usage will trigger a user warning unless explicitly approved via `@escape('raw', $var)`.

### Custom Directives

[](#custom-directives)

Extend the compiler with your own directives:

```
$view->addDirective('datetime', function ($expression) {
    return "";
});
```

Usage: `@datetime($timestamp)`

### Custom Filters

[](#custom-filters)

Register custom filters accessible via pipe syntax `|`:

```
$view->addFilter('upper', function ($value) {
    return strtoupper($value);
});
```

Usage: `{{ $name | upper }}`Chainable: `{{ $name | lower | ucfirst }}`Arguments: `{{ $name | limit(10) }}`

---

14 · Namespaces &amp; Theming
-----------------------------

[](#14--namespaces--theming)

### View Namespaces

[](#view-namespaces)

Register namespaces to organize views (e.g. for packages or modules):

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

Usage: `ui::alert` resolves to `/vendor/ui-lib/views/alert.ml.php`.

### Theming System

[](#theming-system)

MLView supports view cascading and theming.

**1. Multiple View Paths:**

```
$view->addViewPath('/path/to/my/overrides');
```

Loader checks paths in order. If `home` is requested, it checks `/overrides/home.ml.php` then default path.

**2. Theme Activation:**

```
$view->setTheme('dark');
// assumes themes are in resources/themes/dark, prepends this path.
```

**3. Namespace Overrides:**Themes can override namespaced views by following the directory convention: `themes/{theme}/vendor/{namespace}/{view}.ml.php`. For example, `themes/dark/vendor/ui/alert.ml.php` will override `ui::alert`.

---

15 · Production Tooling
-----------------------

[](#15--production-tooling)

MLView includes a CLI tool to help maintain your templates.

### Linting

[](#linting)

The linter scans your templates for:

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

**Usage:**

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

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

If any errors are found, the command exits with a non-zero status code, making it suitable for CI/CD pipelines.

### Compatibility

[](#compatibility)

MLView maintains a compatibility test suite to ensure that standard Blade features work as expected, ensuring a smooth migration path from other engines.

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance88

Actively maintained with recent releases

Popularity21

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 83.8% 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 ~21 days

Total

12

Last Release

60d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/51e4df19377776baa8eafb605d9e7d2374b855c686f552c20d6856e94e3597c3?d=identicon)[yorchperaza](/maintainers/yorchperaza)

---

Top Contributors

[![yorchperaza](https://avatars.githubusercontent.com/u/2913369?v=4)](https://github.com/yorchperaza "yorchperaza (31 commits)")[![Amanar-Marouane](https://avatars.githubusercontent.com/u/155680356?v=4)](https://github.com/Amanar-Marouane "Amanar-Marouane (6 commits)")

###  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

[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)[symfony/ux-icons

Renders local and remote SVG icons in your Twig templates.

555.8M69](/packages/symfony-ux-icons)

PHPackages © 2026

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