Repository navigation
Views and Templates
The Machinjiri View Engine is a lightweight but feature-rich templating system inspired by Laravel's Blade. It compiles your templates into plain PHP files, giving you:
- Zero runtime overhead — templates are compiled once and cached
-
Clean, readable syntax —
@if,@foreach,{{ $var }}and more - Layout inheritance — extend layouts, define sections, and yield content
-
Secure by default — automatic HTML escaping with
{{ }} - Flexible rendering — views, layouts, and fragments
- Asset management — fingerprint assets with cache-busting query strings
- Path traversal protection — views are sandboxed to their base directory
┌─────────────┐ compile ┌─────────────┐ include ┌──────────┐
│ .view.php │ ───────────────▶ │ cache .php │ ───────────────▶ │ Output │
│ (template) │ │ (plain PHP)│ │ (HTML) │
└─────────────┘ └─────────────┘ └──────────┘
When you render a view:
- The renderer resolves the template file (e.g.
home.view.php) - If the cache is stale or missing, the compiler converts directives to PHP
- The compiled PHP is executed with your data extracted into local variables
- The output is returned as a string (or printed via
display())
// resources/views/greeting.view.php
// <h1>Hello, {{ $name }}!</h1>
use Mlangeni\Machinjiri\Core\Views\View;
$html = View::make('greeting', ['name' => 'World'])->render();
echo $html; // <h1>Hello, World!</h1>
// Or render and print directly:
View::make('greeting', ['name' => 'World'])->display();The engine recognizes three file types, each mapped to a suffix:
| Type | Suffix | Purpose |
|---|---|---|
view |
.view.php |
Main page templates |
layout |
.layout.php |
Base layouts extended by views |
fragment |
.frag.php |
Reusable partials (includes) |
View names use dot notation to represent subdirectories:
| View name | Resolved file |
|---|---|
home |
resources/views/home.view.php |
users.index |
resources/views/users/index.view.php |
users.show |
resources/views/users/show.view.php |
admin.dashboard |
resources/views/admin/dashboard.view.php |
partials.header |
resources/views/partials/header.frag.php |
You can pass the type explicitly:
View::make('users.index')->render(); // expects .view.php
View::include('partials.header'); // expects .frag.phpNote: The
include()directive automatically uses thefragmenttype. When you extend a layout, the type islayout. The main render usesview.
Escaped output (recommended) — HTML-escaped automatically:
{{ $username }}
{{ $user['email'] }}
{{ $user->name }}
{{ $name ?? 'Guest' }}
{{ strtoupper($title) }}Compiles to:
<?php echo htmlspecialchars((string)($username), ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8"); ?>Raw output — no escaping (use with trusted content only):
{!! $htmlContent !!}Compiles to:
<?php echo $htmlContent; ?>
⚠️ Security warning: Only use{!! !!}with content you trust. Never echo user input this way.
Blade-style comments are stripped entirely from the output:
{{-- This comment is removed from the compiled output --}}
{{-- Multi-line
comments are supported --}}Tip: Use
{{-- --}}comments instead of<!-- -->for anything containing sensitive info or to save bytes. HTML comments are sent to the browser.
To output a literal @ (for example, in an email address or @media in CSS), double it:
<p>Contact us at info@@example.com</p>
{{-- Output: Contact us at info@example.com --}}
<style>
@@media (min-width: 768px) { /* ... */ }
</style>@if($user->isAdmin())
<span class="badge">Admin</span>
@elseif($user->isModerator())
<span class="badge">Moderator</span>
@else
<span>Member</span>
@endif
{{-- Negated --}}
@unless($isPublic)
<p>This content is private.</p>
@endunless
{{-- Existence checks --}}
@isset($records)
<p>Found {{ count($records) }} records.</p>
@endisset
@empty($records)
<p>No records found.</p>
@endemptyStandard foreach:
@foreach($users as $user)
<li>{{ $user->name }}</li>
@endforeachFor loop:
@for($i = 0; $i < 10; $i++)
<p>Iteration {{ $i }}</p>
@endforWhile loop:
@while($hasMore)
<p>Processing...</p>
{{-- modify $hasMore somehow --}}
@endwhileForelse (with empty handling):
@forelse($posts as $post)
<article>{{ $post->title }}</article>
@empty
<p>No posts yet.</p>
@endforelseLoop control:
@foreach($items as $item)
@continue($item->hidden)
@break($loop->index > 100) {{-- or use your own condition --}}
<p>{{ $item->name }}</p>
@endforeachNote: The
@continueand@breakdirectives also work with a condition:@continue($condition)and@break($condition).
@switch($status)
@case('active')
<span class="text-green">Active</span>
@break
@case('pending')
<span class="text-yellow">Pending</span>
@break
@default
<span class="text-gray">Unknown</span>
@endswitchImportant: The compiler emits
switch ($x):andcase $x:syntax. You must include explicit@breakstatements yourself — the engine does not add them automatically.
Layouts let you define a common page skeleton once, then inject content from child views.
In a child view:
{{-- resources/views/users/profile.view.php --}}
@extends('layouts.app')
@section('title', 'User Profile')
@section('content')
<h1>{{ $user->name }}</h1>
<p>Email: {{ $user->email }}</p>
@endsectionSections capture output between @section and @endsection:
@section('content')
<p>This entire block is captured into the "content" section.</p>
@endsectionA shorthand form sets section content inline (no @endsection):
@section('title', 'My Page Title')Multiple closing directives are supported: @endsection, @stop, @append, @overwrite.
In the layout, use @yield to place section content:
{{-- resources/views/layouts/app.layout.php --}}
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
@yield('content')
<footer>
@yield('footer', 'Default footer text')
</footer>
</body>
</html>Note: The second argument to
@yieldis currently used as a default string argument, but the compiler passes it toView::yield()which only accepts the section name. To set defaults, use@section('footer', '...')in the layout or check with@hasSection.
When a child view overrides a section and wants to include the parent's content, use @parent:
{{-- Layout --}}
@section('sidebar')
<nav>Main navigation</nav>
@endsection
{{-- Child view --}}
@extends('layouts.app')
@section('sidebar')
@parent
<nav>Child-specific links</nav>
@endsectionThe @parent directive restores the previous content that the section held before the child re-opened it.
@hasSection('sidebar')
<aside>@yield('sidebar')</aside>
@endif
@sectionMissing('footer')
<footer>Fallback footer</footer>
@endif@show is a shortcut that closes the current section and immediately yields it:
{{-- In a layout --}}
@section('content')
<p>Default content if child doesn't override</p>
@showThis is equivalent to:
@section('content')
<p>Default content</p>
@endsection
@yield('content')Include another template using @include. The included file uses the fragment type suffix (.frag.php).
{{-- Basic include --}}
@include('partials.header')
{{-- Include with data --}}
@include('partials.user-card', ['user' => $user])
{{-- Include if it exists --}}
@includeIf('partials.ad-banner')
{{-- Include conditionally --}}
@includeWhen($user->isAdmin(), 'partials.admin-toolbar')
@includeUnless($isGuest, 'partials.member-menu')When you include a partial, data is merged in this order (later wins):
-
ViewConfig::$shared(globally shared data) - The parent view's
$data - Explicit data passed to
@include
@include('partials.greeting', ['name' => 'Alice'])
{{-- Even if the parent had $name = 'Bob', the partial sees 'Alice' --}}Fragments should not open sections they don't close. If a fragment leaves a section open, the engine detects this, logs a warning, and force-closes the dangling sections to prevent output buffer corruption.
{{-- BAD: fragment opens a section --}}
@section('header')
<h1>Hi</h1>
{{-- no @endsection --}}Best practice: Fragments should be self-contained. Don't declare sections inside
.frag.phpfiles.
Stacks let you collect content from multiple places (often child views) and output it in one location (often a layout). This is perfect for per-page CSS or JS.
@push('scripts')
<script src="/js/page-specific.js"></script>
@endpush@prepend('styles')
<link rel="stylesheet" href="/css/critical.css">
@endprepend{{-- layouts/app.layout.php --}}
<head>
@stack('styles')
</head>
<body>
@yield('content')
@stack('scripts')
</body>The output order is: all prepended content first, then all pushed content, in the order they were added.
{{-- layouts/app.layout.php --}}
<html>
<head>
<link rel="stylesheet" href="/css/app.css">
@stack('styles')
</head>
<body>
@yield('content')
@stack('scripts')
</body>
</html>{{-- users/index.view.php --}}
@extends('layouts.app')
@push('styles')
<link rel="stylesheet" href="/css/users.css">
@endpush
@section('content')
<h1>All Users</h1>
@endsection
@push('scripts')
<script src="/js/users.js"></script>
@endpushNote: Stacks persist across renders within the same request via
ViewConfig::$stacks. CallViewConfig::flushStacks()if you need to reset them between full renders (e.g. in tests or long-running workers).
The AssetManager provides helpers for linking CSS and JS files with automatic cache busting (a ?v=<mtime> query string).
ViewConfig::setAssetsPath('/var/www/app/public/src'); // filesystem path
ViewConfig::setAssetsUrl('/src'); // public URL{{-- In a template --}}
<link rel="stylesheet" href="{{ View::asset('css/app.css') }}">
{{-- Output: <link rel="stylesheet" href="/src/css/app.css?v=1700000000"> --}}
<script src="{{ View::asset('js/app.js') }}"></script>These emit the full tag for you, with attribute support:
{{ View::style('css/app.css') }}
{{-- <link rel="stylesheet" href="/src/css/app.css?v=..."> --}}
{{ View::style('css/print.css', ['media' => 'print']) }}
{{-- <link rel="stylesheet" href="/src/css/print.css?v=..." media="print"> --}}
{{ View::script('js/app.js') }}
{{-- <script src="/src/js/app.js?v=..."></script> --}}
{{ View::script('js/async.js', ['defer' => true, 'async' => true]) }}
{{-- <script src="/src/js/async.js?v=..." defer async></script> --}}Attribute rules:
-
['key' => 'value']→key="value" -
['defer' => true]→defer(boolean true) -
['defer' => false]→ omitted (boolean false) -
['value'](numeric key) →value
- The timestamp is
filemtime()of the asset file - A bounded cache of 512 timestamps is kept to avoid repeated
stat()calls - Call
AssetManager::flushTimestampCache()to invalidate (e.g. after a deploy)
use Mlangeni\Machinjiri\Core\Views\Services\AssetManager;
// After changing assets
(new AssetManager())->flushTimestampCache();asset() rejects paths containing .. or NUL bytes to prevent traversal:
View::asset('../secrets.env'); // throws MachinjiriExceptionNamespaces let you ship views from packages under a vendor prefix.
use Mlangeni\Machinjiri\Core\Views\Config\ViewConfig;
ViewConfig::addNamespace('admin', __DIR__ . '/vendor/acme/admin-views');Use namespace::path.to.view syntax:
@extends('admin::layouts.panel')
@include('admin::partials.sidebar')This resolves to:
vendor/acme/admin-views/layouts/panel.layout.php
vendor/acme/admin-views/partials/sidebar.frag.php
View::addNamespace('reports', __DIR__ . '/views/reports');Note: Namespace paths are canonicalised with
realpath()at registration time, and views inside are still subject to path-traversal checks.
Data available to every view:
use Mlangeni\Machinjiri\Core\Views\Config\ViewConfig;
ViewConfig::share('appName', 'My App');
ViewConfig::share('user', $currentUser);
// Or pass an array
ViewConfig::share([
'appName' => 'My App',
'version' => '1.0.0',
]);Shared data is merged with per-render data (per-render wins):
View::make('home', ['title' => 'Home']);
// $title = 'Home', $appName = 'My App'Composers run before a view is rendered and let you inject data dynamically:
ViewConfig::composer('dashboard', function ($view) use ($container) {
$view->with('stats', $container->get('stats-service')->getStats());
$view->with('user', auth()->user());
});Composers only run for the view they're registered against — not for layouts or includes (though the layout can access data set on the parent view via $this->data).
$view = View::make('home')
->with('title', 'Welcome')
->with('user', $user);
echo $view->render();These directives let templates react to auth state and environment without clutter:
@auth
<p>Welcome back, {{ auth()->user()->name }}!</p>
@endauth
@guest
<p>Please <a href="/login">log in</a>.</p>
@endguest
@env('staging')
<div class="banner">Staging environment</div>
@endenv
@production
<script src="/js/analytics.js"></script>
@endproductionNote:
@auth/@guestrequireauth()to be defined and to return an object with acheck()method.@envand@productionrequireenv()to be defined. If these functions don't exist in your project, the conditions evaluate to false (safely skipping the block).
You can write raw PHP directly in templates:
@php
$total = 0;
foreach ($items as $item) {
$total += $item->price;
}
@endphp
<p>Total: {{ number_format($total, 2) }}</p>Or use the @php directive as a single statement prefix:
@php $now = new DateTime(); @endphpNote:
@phpcompiles to<?php(with a trailing space). It's designed for the block form shown above. For one-liners, prefer{{ ... }}with a helper method.
@dd($complexData) {{-- var_dump + die (uses dd() if defined) --}}
@dump($complexData) {{-- var_dump (uses dump() if defined) --}}
⚠️ Never ship@dd/@dumpto production.
<form method="POST" action="/users">
@csrf
{{-- Emits csrf_field() if defined, otherwise "" --}}
@method('PUT')
{{-- Emits method_field('PUT') if defined, otherwise "" --}}
</form>For backward compatibility with Machinjiri templates, the engine supports <% %> directives alongside @ directives:
<% extend('layouts.app') %>
<% section('content') %>
<h1>Hello</h1>
<% endsection %>
<% if($isAdmin) %>
<p>Admin area</p>
<% endif %>
<% foreach($users as $user) %>
<li><% yield('name') %></li>
<% endforeach %>All common directives have legacy equivalents: extend, section, endsection, parent, yield, include, if, elseif, else, endif, foreach, endforeach, forelse, empty, endforelse, for, endfor, while, endwhile, push, endpush, prepend, endprepend, stack, php, endphp, hasSection, and content (which yields 'content').
Recommendation: New templates should use
@syntax. Legacy syntax is provided for migration only.
Compiled templates are cached in ViewConfig::getCachePath(). The renderer recompiles automatically when the source file is newer than the cache.
View::clearCache();
// Returns the number of files removedPrecompile all views (useful for production deploys):
View::warmCache(); // compile all .view/.layout/.frag files
View::warmCache('admin'); // compile only under resources/views/admin/
// Returns the number of files compiled- Read the source file
- Strip
{{-- --}}comments - Replace
@@with a placeholder token - Apply all directive patterns in order (most specific first)
- Restore the literal
@placeholder - Write to a temp file, then atomically
rename()to the final cache path
Atomic writes mean concurrent requests never read a half-written cache file.
Cache files are named md5($sourcePath) . '.php'. This means:
- A cache file exists per source file, regardless of view name
- Moving a view source creates a new cache entry
- Stale entries remain until
clearCache()is called
The engine takes several precautions:
{{ }} escapes via htmlspecialchars() with ENT_QUOTES | ENT_SUBSTITUTE. This protects against XSS.
Only
{!! !!}outputs raw content. Audit every use of{!! !!}in your codebase.
- View names use dot notation and are converted to paths without allowing
.or..segments in the way you'd expect — but the resolver does the real safety check -
ViewRenderer::safeResolve()callsrealpath()on both root and candidate and verifies the resolved file is inside the root - Asset paths reject
..and NUL bytes
@extends('../../etc/passwd') throws a ViewEngineException because extendInternal() rejects names containing ...
Namespace paths are canonicalised with realpath() at registration time — symlinks are resolved, and invalid paths are rejected.
-
display()catchesViewEngineExceptionand calls$e->show()if available - Other exceptions are logged and a generic
<!-- Internal view error -->is emitted -
__toString()catches everything and returns an HTML comment
Production tip: Never enable verbose error output in production. The engine logs raw errors to
error_logand keeps HTTP responses clean.
Sections, stacks, and includes all use ob_start() / ob_get_clean(). If a template throws mid-render, finally blocks close dangling buffers, preventing cross-request buffer leakage.
render() enforces MAX_RENDER_DEPTH = 50 to protect against infinite recursion (e.g. a view that includes itself):
// Throws ViewEngineException: "Max render depth exceeded for view: x"Nested renders (via @include, or a view rendering another view instance) increment a depth counter. The current depth is per-instance; the limit is 50.
$view = View::make('home');
echo $view->render(); // depth 1
// Nesting more than 50 levels throws ViewEngineExceptionEvery render() pushes the instance onto View::$instanceStack. Directives like @section, @yield, and @include operate on the top of the stack. This is what makes nested views work correctly:
// Inside a fragment included from a view:
View::section('x'); // operates on the fragment's View instanceNote: Includes share the parent's sections/data but push a new instance for the duration of the include so cleanup works correctly.
ViewRenderer::evaluate() uses EXTR_OVERWRITE, meaning extract() overwrites existing variables. This lets templates intentionally shadow extracted values — matching Blade behaviour.
Internal variables in evaluate() are prefixed with __ to avoid collisions:
protected function evaluate(string $__viewCacheFile, array $__viewData): string
{
return (function (string $__viewCacheFile, array $__viewData): string {
extract($__viewData, EXTR_OVERWRITE);
// ...
})($__viewCacheFile, $__viewData);
}@stack outputs all prepended content first (in prepend order), then all pushed content (in push order):
@prepend('scripts') A @endprepend
@push('scripts') C @endpush
@prepend('scripts') B @endprepend
@stack('scripts')
// Output: A, B, CSections are stored as strings on the active View instance. A child re-opening a section stores the previous content in parentSections, which @parent restores:
// Layout declares:
@section('sidebar') NAV @endsection
// Child reopens:
@section('sidebar') @parent + MORE @endsection
// Result: "NAV + MORE"| Method | Description |
|---|---|
View::share($key, $value) |
Share data with all views |
View::composer($view, $callback) |
Register a composer for a view |
View::addNamespace($ns, $path) |
Register a namespaced view root |
View::setAssetsPath($path) |
Set filesystem path for assets |
View::setAssetsUrl($url) |
Set public URL for assets |
View::asset($path) |
Resolve an asset URL with cache-busting |
View::style($path, $attrs) |
Print a <link rel="stylesheet">
|
View::script($path, $attrs) |
Print a <script> tag |
View::make($view, $data) |
Create a View instance |
View::section($name, $content) |
Open/assign a section |
View::endSection() |
Close the current section |
View::yield($name) |
Output a section |
View::extend($layout) |
Declare a layout |
View::parent() |
Restore parent section content |
View::include($view, $data) |
Include a fragment |
View::hasSection($name) |
Check if a section exists and is non-empty |
View::getSection($name) |
Get section content as a string |
View::push($name) |
Start a push block |
View::endPush() |
End a push block |
View::prepend($name) |
Start a prepend block |
View::endPrepend() |
End a prepend block |
View::stack($name) |
Output a stack |
View::clearCache() |
Delete all compiled views |
View::warmCache($subPath) |
Precompile views |
View::viewExists($view) |
Check if a view file exists |
View::show() |
Close and yield the current section |
| Method | Description |
|---|---|
new View($view, $data) |
Construct a view |
$view->render() |
Render and return a string |
$view->display() |
Render and print (with error handling) |
$view->with($key, $value) |
Add data fluently |
$view->__toString() |
Render (catches errors) |
| Method | Description |
|---|---|
ViewConfig::share(...) |
Add shared data |
ViewConfig::composer($view, $cb) |
Register a composer |
ViewConfig::addNamespace($ns, $path) |
Register a namespace |
ViewConfig::setBasePath($path) |
Set the views root |
ViewConfig::getBasePath() |
Get the views root |
ViewConfig::setCachePath($path) |
Set the cache directory |
ViewConfig::getCachePath() |
Get the cache directory |
ViewConfig::setAssetsPath($path) |
Set assets root |
ViewConfig::getAssetsPath() |
Get assets root |
ViewConfig::setAssetsUrl($url) |
Set assets URL |
ViewConfig::getAssetsUrl() |
Get assets URL |
ViewConfig::ensureStack($name) |
Initialise a stack |
ViewConfig::flushStacks() |
Clear all stacks |
| Method | Description |
|---|---|
asset($path) |
URL with ?v=mtime
|
style($path, $attrs) |
Print <link>
|
script($path, $attrs) |
Print <script>
|
setAssetsPath($path) |
Set assets root (flushes timestamp cache) |
setAssetsUrl($url) |
Set assets URL |
getAssetsPath() |
Get assets root |
getAssetsUrl() |
Get assets URL |
buildAttributes($attrs) |
Build an HTML attribute string |
flushTimestampCache() |
Clear cached mtimes |
| Method | Description |
|---|---|
resolveViewPath($view, $type) |
Resolve a view name to an absolute path (or null) |
getCacheFilePath($source) |
Get the cache path for a source file |
compileAndInclude($view, $type, $data) |
Compile (if needed) and render |
clearCache() |
Delete all compiled files |
warmCache($subPath) |
Precompile views |
Cause: The resolved path doesn't exist.
Check:
- The file is at
resources/views/users/index.view.php - The base path is configured correctly (
ViewConfig::getBasePath()) - If namespaced, the namespace is registered and the file is under its root
Cause: The resolved file is outside the base path (e.g. via a symlink).
Fix: Ensure all views live under the configured base path. Symlinks pointing outside the base are blocked by design.
Cause: @extends() received a layout name containing ...
Fix: Use dot notation for subdirectories: @extends('admin.layouts.panel'), not @extends('../admin/layouts/panel').
Cause: A view includes itself (directly or indirectly) more than 50 times.
Fix: Check for a recursive @include that never terminates. Usually a loop including a template that includes the parent.
Check:
- The layout uses
@yield('content')with the exact same name - The child uses
@extends('...')— if it's missing, sections defined but never rendered - If
@extendscomes after content, the section may be registered too late — put@extendsat the top of the file - For
@hasSection, remember it returnstrueonly if the section exists and is non-empty
Cause: The path in View::asset('css/app.css') doesn't exist under assetsPath.
Fix: Check ViewConfig::getAssetsPath() and the file location.
Cause: Child views push to a stack, but the layout renders before the child's pushes execute.
Explanation: Layouts are rendered after the child view renders — the child's @push blocks execute first, then the layout's @stack reads the accumulated content. If the stack is empty, check:
- The child calls
@extendsat the top of the file - The layout uses
@stack('name')with the exact same name as the@push - You haven't called
ViewConfig::flushStacks()before the layout renders
Cause: File mtime resolution or caching layer.
Fix:
- Run
View::clearCache() - If using OPcache, it may serve stale compiled PHP — call
opcache_invalidate($cacheFile, true)or configure OPcache to check timestamps - Check that the source file and cache file are on the same filesystem with reliable mtimes
{{ $username }} {{-- ✅ escaped --}}
{!! $username !!} {{-- ❌ XSS risk --}}@extends('layouts.app') {{-- ✅ first line --}}
@section('title', 'Page')If @extends comes after output, the layout mechanism may behave unexpectedly because sections are processed in order.
Fragments (.frag.php) should not declare sections or push to stacks they don't close. Reserve section declaration for views and layouts.
{{-- layout --}}
@stack('styles')
{{-- child --}}
@push('styles') <link href="..."> @endpushThis keeps <head> rendering deterministic and avoids duplicate styles.
// deploy.php
View::clearCache();
View::warmCache();This avoids first-request compilation costs and surfaces compile-time errors before traffic arrives.
If you use the engine in a queue worker or ReactPHP/Swoole context, call ViewConfig::flushStacks() after each request to avoid stack content leaking between jobs.
Set ViewConfig::setAssetsUrl() explicitly in production config rather than relying on auto-detection from $_SERVER.
@includeIf('partials.maintenance-banner')This avoids fatal errors when a partial doesn't exist in a given deployment.
Move loops, calculations, and conditionals into controllers or view models. Templates should mostly render pre-shaped data.
Use display() which handles exceptions gracefully, or catch ViewEngineException yourself. Never enable verbose error reporting to end users.
Machinjiri Docs
- Home
- Learn
- Build
-
Tutorials
- Routing
- Controllers and Middleware
- Views and Templates
- Database ORM
- Eloquent Database ORM
- Errors and Exceptions
- Forms and Validation
- Http
- Events and Logging
- Services and DI
- Security
- Authentication
- Caching
- File System
- Date and Time
- Debugging
- Queue and Jobs
- Task Scheduling
- Transport (Mail, SMS)
- LDAP
- Notifications
- Webhooks
- UUID Generations
- Terminal
- Helper Function
- Reference