Skip to content

Views and Templates

Precious Lyson edited this page Nov 13, 2026 · 2 revisions

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

How It Works

┌─────────────┐     compile      ┌─────────────┐     include      ┌──────────┐
│ .view.php   │ ───────────────▶ │  cache .php │ ───────────────▶ │  Output  │
│ (template)  │                  │  (plain PHP)│                  │  (HTML)  │
└─────────────┘                  └─────────────┘                  └──────────┘

When you render a view:

  1. The renderer resolves the template file (e.g. home.view.php)
  2. If the cache is stale or missing, the compiler converts directives to PHP
  3. The compiled PHP is executed with your data extracted into local variables
  4. The output is returned as a string (or printed via display())

Rendering Your First View

// 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();

View Files & Types

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 Naming with Dots

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.php

Note: The include() directive automatically uses the fragment type. When you extend a layout, the type is layout. The main render uses view.


Basic Syntax

Echoing Data

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.

Comments

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.

Escaping the @ Symbol

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>

Control Structures

Conditionals

@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>
@endempty

Loops

Standard foreach:

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

For loop:

@for($i = 0; $i < 10; $i++)
    <p>Iteration {{ $i }}</p>
@endfor

While loop:

@while($hasMore)
    <p>Processing...</p>
    {{-- modify $hasMore somehow --}}
@endwhile

Forelse (with empty handling):

@forelse($posts as $post)
    <article>{{ $post->title }}</article>
@empty
    <p>No posts yet.</p>
@endforelse

Loop control:

@foreach($items as $item)
    @continue($item->hidden)
    @break($loop->index > 100)  {{-- or use your own condition --}}
    <p>{{ $item->name }}</p>
@endforeach

Note: The @continue and @break directives also work with a condition: @continue($condition) and @break($condition).

Switch Statements

@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>
@endswitch

Important: The compiler emits switch ($x): and case $x: syntax. You must include explicit @break statements yourself — the engine does not add them automatically.


Layouts & Sections

Layouts let you define a common page skeleton once, then inject content from child views.

Extending Layouts

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>
@endsection

Defining Sections

Sections capture output between @section and @endsection:

@section('content')
    <p>This entire block is captured into the "content" section.</p>
@endsection

A shorthand form sets section content inline (no @endsection):

@section('title', 'My Page Title')

Multiple closing directives are supported: @endsection, @stop, @append, @overwrite.

Yielding Content

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 @yield is currently used as a default string argument, but the compiler passes it to View::yield() which only accepts the section name. To set defaults, use @section('footer', '...') in the layout or check with @hasSection.

Section Inheritance

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>
@endsection

The @parent directive restores the previous content that the section held before the child re-opened it.

Conditional Sections

@hasSection('sidebar')
    <aside>@yield('sidebar')</aside>
@endif

@sectionMissing('footer')
    <footer>Fallback footer</footer>
@endif

The @show Directive

@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>
@show

This is equivalent to:

@section('content')
    <p>Default content</p>
@endsection
@yield('content')

Includes & Partial Views

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')

Data Merging in Includes

When you include a partial, data is merged in this order (later wins):

  1. ViewConfig::$shared (globally shared data)
  2. The parent view's $data
  3. Explicit data passed to @include
@include('partials.greeting', ['name' => 'Alice'])
{{-- Even if the parent had $name = 'Bob', the partial sees 'Alice' --}}

Fragment Hygiene

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.php files.


Stacks

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 — Append to a Stack

@push('scripts')
    <script src="/js/page-specific.js"></script>
@endpush

@prepend — Prepend to a Stack

@prepend('styles')
    <link rel="stylesheet" href="/css/critical.css">
@endprepend

@stack — Render the Stack

{{-- 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.

Example: Page-Specific Assets

{{-- 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>
@endpush

Note: Stacks persist across renders within the same request via ViewConfig::$stacks. Call ViewConfig::flushStacks() if you need to reset them between full renders (e.g. in tests or long-running workers).


Assets Management

The AssetManager provides helpers for linking CSS and JS files with automatic cache busting (a ?v=<mtime> query string).

Setup

ViewConfig::setAssetsPath('/var/www/app/public/src');  // filesystem path
ViewConfig::setAssetsUrl('/src');                      // public URL

Basic Usage

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

@style and @script Helpers

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

Cache-Busting Details

  • 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 Path Security

asset() rejects paths containing .. or NUL bytes to prevent traversal:

View::asset('../secrets.env');  // throws MachinjiriException

Namespaced Views

Namespaces let you ship views from packages under a vendor prefix.

Registering a Namespace

use Mlangeni\Machinjiri\Core\Views\Config\ViewConfig;

ViewConfig::addNamespace('admin', __DIR__ . '/vendor/acme/admin-views');

Referencing Namespaced 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

Static Helper

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.


View Composers & Shared Data

Shared Data

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'

View Composers

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).

Fluent Instance API

$view = View::make('home')
    ->with('title', 'Welcome')
    ->with('user', $user);

echo $view->render();

Authentication & Environment Directives

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>
@endproduction

Note: @auth / @guest require auth() to be defined and to return an object with a check() method. @env and @production require env() to be defined. If these functions don't exist in your project, the conditions evaluate to false (safely skipping the block).


PHP Code in Views

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(); @endphp

Note: @php compiles to <?php (with a trailing space). It's designed for the block form shown above. For one-liners, prefer {{ ... }} with a helper method.

Debugging Helpers

@dd($complexData)       {{-- var_dump + die (uses dd() if defined) --}}
@dump($complexData)     {{-- var_dump (uses dump() if defined) --}}

⚠️ Never ship @dd / @dump to production.

CSRF & Method Spoofing

<form method="POST" action="/users">
    @csrf
    {{-- Emits csrf_field() if defined, otherwise "" --}}

    @method('PUT')
    {{-- Emits method_field('PUT') if defined, otherwise "" --}}
</form>

Legacy Syntax

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.


Cache Management

Compiled templates are cached in ViewConfig::getCachePath(). The renderer recompiles automatically when the source file is newer than the cache.

Clear the Cache

View::clearCache();
// Returns the number of files removed

Warm the Cache

Precompile 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

How Compilation Works

  1. Read the source file
  2. Strip {{-- --}} comments
  3. Replace @@ with a placeholder token
  4. Apply all directive patterns in order (most specific first)
  5. Restore the literal @ placeholder
  6. 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 File Naming

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

Security

The engine takes several precautions:

1. Automatic Escaping

{{ }} escapes via htmlspecialchars() with ENT_QUOTES | ENT_SUBSTITUTE. This protects against XSS.

Only {!! !!} outputs raw content. Audit every use of {!! !!} in your codebase.

2. Path Traversal Prevention

  • 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() calls realpath() on both root and candidate and verifies the resolved file is inside the root
  • Asset paths reject .. and NUL bytes

3. Layout Name Validation

@extends('../../etc/passwd') throws a ViewEngineException because extendInternal() rejects names containing ...

4. Namespace Registration

Namespace paths are canonicalised with realpath() at registration time — symlinks are resolved, and invalid paths are rejected.

5. Error Handling

  • display() catches ViewEngineException and 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_log and keeps HTTP responses clean.

6. Output Buffer Cleanup

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.

7. Render Depth Limit

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"

Advanced Topics

Render Depth

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 ViewEngineException

Instance Stack

Every 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 instance

Note: Includes share the parent's sections/data but push a new instance for the duration of the include so cleanup works correctly.

Data Shadowing

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);
}

Prepend vs Push Ordering

@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, C

Section Content Resolution

Sections 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"

API Reference

Static Methods on View

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

Instance Methods

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)

ViewConfig Statics

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

AssetManager Methods

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

ViewRenderer Methods

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

Troubleshooting

"View file not found: users.index (type: view)"

Cause: The resolved path doesn't exist.

Check:

  1. The file is at resources/views/users/index.view.php
  2. The base path is configured correctly (ViewConfig::getBasePath())
  3. If namespaced, the namespace is registered and the file is under its root

"View path escapes base directory"

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.

"Invalid layout name: ..."

Cause: @extends() received a layout name containing ...

Fix: Use dot notation for subdirectories: @extends('admin.layouts.panel'), not @extends('../admin/layouts/panel').

"Max render depth exceeded"

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.

Section content missing / empty

Check:

  1. The layout uses @yield('content') with the exact same name
  2. The child uses @extends('...') — if it's missing, sections defined but never rendered
  3. If @extends comes after content, the section may be registered too late — put @extends at the top of the file
  4. For @hasSection, remember it returns true only if the section exists and is non-empty

"Asset file not found: ..."

Cause: The path in View::asset('css/app.css') doesn't exist under assetsPath.

Fix: Check ViewConfig::getAssetsPath() and the file location.

Stacks empty in a layout

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:

  1. The child calls @extends at the top of the file
  2. The layout uses @stack('name') with the exact same name as the @push
  3. You haven't called ViewConfig::flushStacks() before the layout renders

Template doesn't recompile after edits

Cause: File mtime resolution or caching layer.

Fix:

  1. Run View::clearCache()
  2. If using OPcache, it may serve stale compiled PHP — call opcache_invalidate($cacheFile, true) or configure OPcache to check timestamps
  3. Check that the source file and cache file are on the same filesystem with reliable mtimes

Best Practices

1. Always escape user input

{{ $username }}          {{-- ✅ escaped --}}
{!! $username !!}        {{-- ❌ XSS risk --}}

2. Put @extends at the top

@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.

3. Keep fragments self-contained

Fragments (.frag.php) should not declare sections or push to stacks they don't close. Reserve section declaration for views and layouts.

4. Use stacks for per-page assets

{{-- layout --}}
@stack('styles')

{{-- child --}}
@push('styles') <link href="..."> @endpush

This keeps <head> rendering deterministic and avoids duplicate styles.

5. Warm the cache on deploy

// deploy.php
View::clearCache();
View::warmCache();

This avoids first-request compilation costs and surfaces compile-time errors before traffic arrives.

6. Flush stacks between renders in long-running processes

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.

7. Pin asset URLs in production

Set ViewConfig::setAssetsUrl() explicitly in production config rather than relying on auto-detection from $_SERVER.

8. Use @includeIf for optional partials

@includeIf('partials.maintenance-banner')

This avoids fatal errors when a partial doesn't exist in a given deployment.

9. Avoid logic-heavy templates

Move loops, calculations, and conditionals into controllers or view models. Templates should mostly render pre-shaped data.

10. Log, don't leak, errors in production

Use display() which handles exceptions gracefully, or catch ViewEngineException yourself. Never enable verbose error reporting to end users.


Clone this wiki locally