Luminova Framework

PHP Luminova: View Template Rendering

Last updated: 2026-11-28 20:57:12

Render PHP, Smarty, or Twig views with optional output caching.

Luminova’s Template View Rendering class loads templates and renders them with data supplied by a controller. It supports the default PHP engine, Smarty, and Twig. The view can render HTML or other formats and cache the rendered output when caching is enabled. See Template Caching for configuring expiry and managing cached views.


Features

  1. Fast Rendering – Compiles and minifies templates automatically.
  2. Flexible Output – Supports templates that return HTML, arrays, objects, or scalars.
  3. Built-in Caching – Saves rendered templates for better performance.
  4. Highly Configurable – Adjust rendering modes via Template Rendering Configuration.

Template Rendering Modes

Luminova allows you render templates in two ways: Global Mode (the default) or Isolation Mode.You can switch modes in the Template View Configuration.

Global Mode

Global mode gives your template direct access to view class object using $this.That means the template can reach:

  • view-specific properties
  • public methods on the view class
  • application properties through $this->app
// /resources/Views/index.php

// View options
$this->_title;

// Application properties
$this->app->propertyName;

Use this when:

You want simple access to everything with no extra setup.Good for quick builds or templates that talk to the application often.


Isolation Mode

In isolation mode, the template cannot use $this or self.Instead, Luminova gives you a clean $self object with only what the view exposes.

// /resources/Views/index.php

// View options
$self->_title;

// Application properties
$self->app->propertyName;

Use this when:

You want a stricter boundary between the template and the rest of the app.Useful for cleaner structure, better security, and easier testing.


Smarty or Twig Templates

When you use Smarty or Twig, you can access the view object and the application instance through a global reference. Smarty uses $self, while Twig uses self.

Smarty Example:

{# /resources/Views/index.tpl #}

{# Smarty View Options #}
{{ $self.title }}

{# Smarty Application Properties #}
{{ $self.app.propertyName }}

Twig Example:

{# /resources/Views/index.tpl #}

{# Twig View Options #}
{{ self.title }}

{# Twig Application Properties #}
{{ self.app.propertyName }}

Note:Auto-prefixing of view options does not apply when using Smarty or Twig. If you wish to prefix options, you can do that in controller before rendering template


Template Scope Options

Luminova makes a set of variables automatically available inside every template.These variables give you details about the current view and help you control how the template behaves.

These options are split into two groups: Immutable (system-controlled) and Mutable (you can override them).


Immutable Options

These are set by the system and cannot be changed when rendering a view.

Note:$scope in the below examples refers to:

  • $this in Global Mode – Refers to the current view class instance. You can access view methods and application properties directly.
  • $self in Isolation Mode – Refers to an instance of Luminova\Template\Engines\Scope, which safely exposes only allowed view properties and the application object.

Note:Accessing $self in non-isolation mode will throw a RuntimeException.It is also recommended not to override $self inside the template file, as it may break the intended scope and guard functionality.


View Template Content Type

Variable Name: tplType (string)

Represents the type of template content being rendered (e.g, html, xml etc..).

Examples:

// resources/Views/example.php

// When variable prefixing is enabled
echo $scope->_tplType; 

// When variable prefixing is disabled
echo $scope->tplType;

Current Template

Variable Name: active (string)

The name of the current template file without the extension (e.g, index, about etc..).

Examples:

// resources/Views/example.php

// When variable prefixing is enabled
echo $scope->_active; 

// When variable prefixing is disabled
echo $scope->active;

Assets

Variable Name: asset (string)

The base path to your public assets directory.

Use it as the starting point before adding the final file path.

Examples:

// resources/Views/example.php ?>

<?php // When variable prefixing is enabled ?>
<img src="<?= $scope->_asset; ?>images/file.png">

<?php // When variable prefixing is disabled ?>
<img src="<?= $scope->asset; ?>images/file.png">

<?php // Result: /assets/images/file.png ?>
{# Smarty #}
<img src="{{ $self.asset }}images/file.png">

{# Twig #}
<img src="{{ self.asset }}images/file.png">

Also a global helper function available e.g, Luminova\Funcs\asset(...) or {{ asset(...) }} in frontend template engin.


Variable Name: href (string)

The base href used for building links.

Examples:

// resources/Views/example.php ?>

<?php // When variable prefixing is enabled ?>
<a href="<?= $scope->_href; ?>about">About Us</a>

<?php // When variable prefixing is disabled ?>
<a href="<?= $scope->href; ?>about">About Us</a>

<?php // Result: /about ?>
{# Smarty #}
<a href="{{ $self.href }}images/file.png">About Us</a>

{# Twig #}
<a href="{{ self.href }}images/file.png">About Us</a>

Also a global helper function available e.g, Luminova\Funcs\href(...) or {{ href(...) }} in frontend template engin.


Access Control

Constant Name: ALLOW_ACCESS (bool: true)

A constant you can use to block direct access to view files.

Examples:

defined('ALLOW_ACCESS') || die('Access to file is not allowed');

// Template contents here

This ensure that only view class can render the template.


Mutable Options

These values can be overridden when rendering a template.

Template Cache

Variable Name: noCache (bool)

If true, the template will be skipped by the caching system if caching is enabled (see env('page.caching')), and the template name is added to the exclusion list for the current request.

Examples:

// /app/Controllers/Http/MyController.php

public function posts(): int 
{
    return $this->view('posts', [
        'noCache' => true
    ]);
}

Page Title

Variable Name: title (string)

The current page title.If not set, Luminova uses: "<active template>" – "<application name>"

Examples:

// /app/Controllers/Http/MyController.php

public function posts(): int 
{
    return $this->view('posts', [
        'title' => 'My Blog Post'
    ]);
}

Page Subtitle

Variable Name: subtitle (string)

The current page subtitle.If not set, it falls back to the formatted template name without the application name suffix.

Examples:

// /app/Controllers/Http/MyController.php

public function posts(): int 
{
    return $this->view('posts', [
        'subtitle' => 'My Blog Post Contents'
    ]);
}

View Scope Options Access

Template options are extra values passed into a view during rendering.How you access them depends on your Template Variable Prefixing setting in the configuration.

Prefixing Enabled

When prefixing is set to TRUE, Luminova adds an underscore (_) before every option key:

$this->_fooOption;
$self->_fooOption;

This applies in both global and isolation modes.


Prefixing Disabled

When prefixing is set to FALSE, options appear as normal property names:

$this->fooOption;
$self->fooOption;

Be careful in isolation mode:Do not use self as an option name, since self is reserved for the isolated scope object.


Raw Options

With prefixing set to NULL, Luminova skips property injection and exposes the raw $options array directly:

$options['fooOption'];

This works the same way in both rendering modes.

You can also fetch values manually using the view helper methods:getOption() and getOptions().


Accessing Application Properties

Inside any template, you always have access to your main application instance through $app.

Both protected and public properties or methods in your App\Application class become available.

// /app/Application.php
namespace App;

use Luminova\Sessions\Session;
use Luminova\Foundation\Core\AbstractApplication as CoreApplication;

class Application extends CoreApplication
{
    protected ?Session $session = null;

    protected function onCreate(): void 
    {
        $this->session = new Session();
        $this->session->setStorage('users');
        $this->session->start();
    }
}

Then inside your view:

// /resources/Views/example.php

$this->app->session->isOnline();

// or in isolation mode
$self->app->session->isOnline();

For exporting properties in a controlled way, see the export() method in this template view documentation.


Other Variables

  • Variable Name: $_VIEW_FILEPATH (string) The absolute file path to the current template.
  • Variable Name: $_VIEW_TYPE (string) The template view content type.

Examples:

// resources/Views/example.php

echo $_VIEW_FILEPATH; 
// /path/application/resources/Views/example.php

echo $_VIEW_TYPE;
// html

Template Contents

Luminova templates support two main ways to provide content: direct output or returning content. How the content is processed depends on its type.

Outputting Content

This is the traditional way, the template directly outputs HTML or text. Use this when you want the template to immediately render to the browser or output buffer.

// resources/Views/example.php ?>

<div>
    <p><?= $this->_user->name; ?></p>
    <a href="mailto:<?= $this->_user->email; ?>"><?= $this->_user->email; ?></a>
</div>

Returning Content

Templates can also return values instead of echoing them. Luminova automatically executes callables and formats the returned data before sending it to the client.

Supported return types and behavior:

TypeOutput Handling
Scalar (string, int, float, bool)Converted to string and sent directly.
SimpleXMLElementConverted to XML via asXML() with Content-Type: application/xml.
DOMDocumentConverted to XML via saveXML() with Content-Type: application/xml.
Stringable ObjectConverted to string via casting to (string) and sent.
CallableExecuted, and its return value is processed recursively using the same rules.
Object with __toString() or toString()Converted to string by calling the method and sent.
Array / Object (otherwise)JSON-encoded and sent with Content-Type: application/json.

Examples:

Returning an array.

// resources/Views/example.php

return [
    'name'  => $this->_user->name,
    'email' => $this->_user->email
];

Returning an object implementing __toString()

return new class($this->_user) {
    public function __construct(private User $user) {}
    public function __toString(): string { 
        return sprintf(
            'Contact %s, via %s',
            $this->user->name,
            $this->user->email
        ); 
    }
};

Returning a DOMDocument.

$dom = new DOMDocument();

$dom->loadXML('
    <user>
        <name>' . $this->_user->name . '</name>
        <email>' . $this->_user->email . '</email>
    </user>'
);

return $dom;

Returning a SimpleXMLElement → sent as XML

$xml = new SimpleXMLElement('<user/>');

$xml->addChild('name', $this->_user->name);
$xml->addChild('email', $this->_user->email);

return $xml;

Returning a callable.

return function(): array 
{
    return ['timestamp' => time()];
};

Note:

Returning arrays or objects (without __toString()/toString()) automatically produces JSON output to the client. Returning scalars, Stringable objects, or XML types are rendered according to their type. Callables are executed before output.Any other content type (e.g. a resource) is unsupported and throws a RuntimeException.

---*

Class Definition


Constants

Template Content Types

These constants define template content type identifiers used by the framework for operations such as caching, minification, and other processing. For more rendering support see Response Class Documentation

ConstantTypeValueDescription
HTMLstring'html'HTML templates or content.
XHTMLstring'xhtml'Strict XHTML templates or content.
JSONstring'json'JSON-formatted content.
TEXTstring'txt'Plain text content.
XMLstring'xml'XML-formatted content.
JSstring'js'JavaScript files or code blocks.
CSSstring'css'CSS stylesheets or inline styles.
RDFstring'rdf'RDF-formatted content for semantic data.
ATOMstring'atom'ATOM feed format.
RSSstring'rss'RSS feed format.
BINstring'bin'Binary string content format.
PNGstring'png'PNG images.
JPEGstring'jpeg'JPEG images.
GIFstring'gif'GIF images.
WEBPstring'webp'WebP images.
SVGstring'svg'SVG images.
AVIFstring'avif'AVIF images.
MP3string'mp3'MP3 audio.
OGGstring'ogg'OGG audio.
WEBMstring'webm'WebM audio or video format.
MP4string'mp4'MP4 video.

Note:

They are not the same as HTTP header Content-Type values, but are used internally for purposes such as caching, minification, and content processing. If no explicit HTTP header content type is set, these constants can also be used to determine the appropriate response header.The string alias 'text' is also accepted as an equivalent input for View::TEXT when calling view().

WEBM note: Must be served with the correct header (audio/webm or video/webm) via header(), otherwise inline playback may fail.

$this->tpl->header('Content-Type', 'audio/webm');

Properties

app

Holds the application instance.

public readonly LazyObjectInterface $app;

Does not create a circular reference with the view instance.

Examples:

$this->app; 
// or  
$self->app;

When to use:Use this property when you need access to application-level services, configuration, or methods directly from within a template without instantiating or passing the application object manually.Use export for private properties.


layout

Holds the default template layout object when the layout system is enabled via App\Config\Template::$enableDefaultTemplateLayout.

public ?Layout $layout = null;

This is initialized internally right before a default (PHP) template is rendered, and is null for third-party engines (Smarty, Twig) or when the layout feature is disabled.


Methods

__construct

Initialize the View object.

This constructor sets up template configuration for view management, and loads environment-based options.

public function __construct(
    AbstractApplication|LazyObjectInterface|null $app = null
)

Parameters:

ParameterTypeDescription
$appApplication|LazyObjectInterface|nullOptional application object, or a lazy-loaded application object.
If omitted, templates will not have access to the application instance via ($this->app or $self->app) until setApplication() is called.

Note:

You may not need to initialize this class manually as it is already available within the Luminova\Foundation\Core\AbstractApplication class, which can be accessed inside controller classes.For global helper access, use Luminova\Funcs\view(...).


setApplication

Set the application object for the template view class after construction.

This is useful when the view instance was created without an application object ($app = null) and needs to be bound later.

public function setApplication(AbstractApplication&LazyObjectInterface $app): self

Parameters:

ParameterTypeDescription
$appAbstractApplication&LazyObjectInterfaceThe application object, or a lazy-loaded application object.

Return:

self - Return instance of template view class.

Throws:

Note:If an application instance has already been set (either via the constructor or a previous call), this method does nothing and returns silently.


view

Sets the view template and its content type for rendering.

It resolves the template path and prepares it for rendering or later access.

Call this method to specify which view file to use, before any of these methods (render(), contents(), promise(), exists() or info()) are called.

Search Paths:

  • /resources/Views/ — MVC view directory.
  • /app/Modules/Views/ — HMVC root view directory.
  • /app/Modules/<Module>/Views/ — HMVC module-specific views.

Supported Content Types:

  • html, xhtml, json, text|txt, xml, js, css, rdf, atom, rss, bin, png, jpeg, gif, webp, svg, avif, mp3, ogg, webm, mp4

The $template must exclude file extensions (.php, .tpl, .twg, etc).For unsupported types, use response(...)->render(...) for manual handling.

public final function view(string $template, string $type = self::HTML): self

Parameters:

ParameterTypeDescription
$templatestringView filename without extension (e.g., dashboard, index).
$typestringThe template content type (default: View::HTML).

Return:

self - Return instance of template view class.

Throws:

Examples:

Usage in Controller:

// /app/Controllers/Http/FooController.php

// Render view and return status
$status = $this->tpl->view('profile', View::HTML)
    ->render(['id' => 1]);

// Render view and return content
$content = $this->tpl->view('settings', View::JSON)
    ->contents(['tab' => 'privacy']);

// Render view and return promise object
$promise = $this->tpl->view('invoice', View::HTML)
    ->promise(['orderId' => 101]);

// Return template filesystem information
$info = $this->tpl->view('index', View::HTML)
    ->info();

Direct Usage:

$view = new View(app: $application);

render

Render and immediately send the view output.

This method renders view content with an optional parameters to make globally availablewithin the template view file.

public final function render(array $options = [], int $status = 200): int

Parameters:

ParameterTypeDescription
$optionsarray<string, mixed>Additional parameters to pass in the template (available inside view).
$statusintThe HTTP status code (default: 200 OK).

Return:

int - Return one of the following status codes:

  • STATUS_SUCCESS if the view is handled successfully,
  • STATUS_SILENCE if failed, silently terminate without error page allowing you to manually handle the state.

Throws:

Examples:

Display template view with options:

// /app/Controllers/Http/FooController.php

public function fooView(): int 
{
    return $this->tpl->view('name')
        ->render(['title' => 'Welcome'], 200);
}

contents

Render the view and return the output as a string.

This method renders selected template view and return the rendered contents string.

public final function contents(array $options = [], int $status = 200): ?string

Parameters:

ParameterTypeDescription
$optionsarray<string, mixed>Additional parameters to pass in the template (available inside view).
$statusintHTTP status code (default: 200 OK).

Return:

string|null - Return the compiled view contents or null if no content.

Throws:

Examples:

Display your template view or send as an email:

// /app/Controllers/Http/MailController.php

use Luminova\Components\Email\Mailer;

public function mailView(): int 
{
    $content = $this->tpl->view('name')
        ->contents(['foo' => 'bar'], 200);

    Mailer::to('[email protected]')->send($content);
}

promise

Return a promise that resolves with rendered view contents.

Renders the template view file and returns a promise that resolves with the rendered contents, or rejects if the template is missing or rendering fails.

public final function promise(array $options = [], int $status = 200): PromiseInterface

Parameters:

ParameterTypeDescription
$optionsarray<string, mixed>Additional parameters to pass in the template (available inside view).
$statusintHTTP status code (default: 200 OK).

Return:

Luminova\Interface\PromiseInterface - Return a promise that resolves with rendered view contents or rejects with an error.

Examples:

Display your template view or send as an email:

// /app/Controllers/Http/FooController.php

public function fooView(): int 
{
    $this->tpl->view('name')
        ->promise(['foo' => 'bar'])
        ->then(function(string $content, array $options) {
            Mailer::to('[email protected]')->send($content);
        })->catch(function(Exception $e) {
            logger('debug', $e->getMessage());
        });

    return STATUS_SUCCESS;
}

exists

Check if a template view file exists (without rendering).

public final function exists(): bool

Return:

bool - Return true if the resolved template matches the requested template name and the file exists on disk, false otherwise.

Note:Returns false when the resolved filename differs from the requested template (for example, when production mode silently falls back to the 4xx error template).

Examples:

if($this->tpl->view('admin')->exists()){
    // Yes
}

info

Returns metadata about the specified view template.

Provides useful diagnostic and contextual information about a template file without rendering.

public final function info(?string $key = null): mixed

Parameters:

ParameterTypeDescription
$keystring|nullOptional key to retrieve a specific value.

Return:

array<string,mixed>|mixed - Return the value for that key (null if not found), otherwise return metadata array.

KeyTypeDescription
locationstringResolved file path.
typestringView content type.
templatestringSelected template name.
enginestringTemplate engine name.
sizeint\|falseFile size in bytes, or zero before a file is resolved.
timestampint\|falseLast modification time, or zero before a file is resolved.
modifiedstringFormatted modification date, or an empty string.
modulestring\|nullHMVC module name when available.
dirnamestring\|nullTemplate directory when available.
extensionstring\|nullTemplate file extension.
filenamestring\|nullTemplate basename without the extension.

Examples:

$info = $this->tpl->view('dashboard')->info();

// Get the modified
$modified = $this->tpl->view('dashboard')->info('modified');

export

Export a class instance or fully qualified name for later access in templates.

This allows registering services, classes, or any custom objectso that it can be accessed in the template via its alias.

public final function export(
    object|string $target,
    ?string $alias = null,
    bool $shared = false
): bool

Parameters:

ParameterTypeDescription
$targetobject|stringThe class name, object instance to expose.
$aliasstring|nullOptional alias for reference (Defaults to class class/object name).
$sharedboolIf true and $target is class name, the same instance will be reused.

Return:

bool - Returns true if imported, otherwise throw error.

Throws:

Examples:

// /app/Controllers/Http/MainController.php

class MainController extends AbstractController
{
    protected function onCreate(): void 
    {
        $session = new Session();
        $session->setStorage('users');
        $session->start();

        // Export the session object for use in views
        $this->tpl->export($session, 'session');
    }
}

Note:If $target is not an object, it’s treated as a class name that will be instantiated later.


Accessing Exported Data in Views

Exported properties can be accessed using their $alias.If no alias is provided, the class basename is used automatically.

// /resources/Views/example.php
$this->session->isOnline();

// or when using isolated mode
$self->session->isOnline();

You can also retrieve exports through the helper method:

// /resources/Views/example.php
$this->getExport('session');
// or
$self->getExport('session');

header

Set a single response header.

This allows you to add a response header for template rendering,

public final function header(string $key, mixed $value): self

Parameters:

ParameterTypeDescription
$keystringThe template response header key.
$valuemixedThe header value for key.

Return:

self - Return instance of template view class.

Examples:

$this->tpl->header('Content-Type', 'application/json');

headers

Set multiple response headers at once.

This allows you to add a custom response headers for template rendering,

public final function headers(array $headers): self

Parameters:

ParameterTypeDescription
$headersarray<string, mixed>Associative array of headers key-pair.

Return:

self - Return instance of template view class.

Throws:

Examples:

$this->tpl->headers([
    'Cache-Control' => 'no-cache',
    'Content-Type' => 'text/html; charset=utf-8',
]);

getHeaders

Get the template response headers.

Returns the prepared headers before rendering. If called after rendering, returns the final headers that were sent.

public function getHeaders(): array

Return:

array<string,mixed> - Returns template headers.

Examples:

$headers = $this->tpl->getHeaders();

setModule

Override the module whose Views/ directory the template engine uses in HMVC mode. The HTTP base controller already supplies its class name, so the view normally infers the module from the controller namespace.

public final function setModule(string $module = '/'): self

Parameters:

ParameterTypeDescription
$modulestringNamed module directory. Leading and trailing forward slashes are trimmed. The resulting name must be non-empty and contain no path separators.

Return:

self - Returns the current view instance.

Throws:

Examples:

$this->tpl->setModule('Shared');
return $this->view('blogs');

Set the override before selecting the template. See HMVC Controllers for automatic root and named-module resolution.


setController

Set the controller class name used by the view.

The HTTP base controller sets this automatically. If you construct a view outside an HTTP controller, set it before the first template lookup to enable namespace-based module inference.

public final function setController(string $controller): self

Parameters:

ParameterTypeDescription
$controllerstringFully qualified controller class name.

Return:

self - Return instance of template view class.

Examples:

$this->tpl->setController(static::class);

Note:This is called automatically by Luminova\Base\Controller and does not typically need to be called manually.


setFolder

Sets the view subfolder used to locate template files within the application template view directory.

Valid base locations include:

  • resources/Views/ - MVC View directory.
  • app/Modules/Views/ - HMVC root view directory.
  • app/Modules/<Module>/Views/ - HMVC custom module view directory.
public final function setFolder(string $folder): self

Parameters:

ParameterTypeDescription
$folderstringSubfolder name to look for views.

Return:

self - Return instance of template view class.

Notes:

  • When used in a controller's onCreate or __construct, all views for that controller will be searched in this folder.
  • When used in a controller method before rendering, only that method's view resolution is affected.

Examples:

In this example, the setFolder method is used to direct the framework to look for template files in a custom directory (resources/Views/admin/) for all views within a specific controller.

// /app/Controllers/Http/AdminController.php

namespace App\Controllers\Http;

use Luminova\Base\Http\AbstractController;

class AdminController extends AbstractController
{
    protected function onCreate(): void
    {
        $this->tpl->setFolder('admin');
    }

    public function dashboard(): int
    {
        return $this->view('dashboard');
    }

    public function login(): int
    {
        // Overrides the default folder for the current method.
        $this->tpl->setFolder('main');

        return $this->view('login');
    }
}

setRelativeDepth

Set URI relative parent directories depth.

This method allows you to manually set how many parent directories (../) to prepend to asset and link paths.

It overrides Luminova's default auto-detection based on the current URI depth.Use it when working with nested views or custom routes that require explicit relative path control.

Example depth values:

  • 1 → ../
  • 2 → ../../
public final function setRelativeDepth(?int $depth): self

Parameters:

ParameterTypeDescription
$depthint|nullNumber of ../ segments to prepend, or null to restore automatic depth detection.

Return:

self - Return instance of template view class.

Useful when custom routing or nested views affect the correct relative path for assets.

Examples:

Force asset paths to go up one directory:

// /app/Controllers/Http/ExampleController.php

namespace App\Controllers\Http;

use Luminova\Attributes\Route;
use Luminova\Base\Http\AbstractController;

class ExampleController extends AbstractController
{
    #[Route('/app/account', methods: ['GET'])]
    public function example(): int
    {
        // Override auto depth detection to use only one "../"
        $this->tpl->setRelativeDepth(1);

        return $this->view('account');
    }
}

In the corresponding view file:

// /resources/Views/account.php

echo Luminova\Funcs\asset('images/logo.png');
// OR
echo "{$this->_asset}images/logo.png";
// Generates: ../assets/images/logo.png

echo Luminova\Funcs\href('account/foo');
// OR
echo "{$this->_href}account/foo";
// Generates: ../account/foo

Normally, accessing https://example.com/app/account would trigger auto-detection of ../../ in development environment like XAMPP due to the URI depth (public/app/account).But since we explicitly set the depth to 1, only a single ../ is prepended to asset and link paths.


htmlMinification

Configure HTML template minification.

Controls template HTML content minification and which HTML tags should have their contents preserved during the minification process, as well as which action buttons (e.g. copy, ai, run) are shown on <code> blocks.

public final function htmlMinification(
    bool $enable,
    ?array $preserveTags = null,
    ?array $codeBlockButtons = null
): self

Parameters:

ParameterTypeDescription
$enableboolWhether to minify the template content.
$preserveTagsstring[]|nullHTML tags whose content should be preserved, such as PRE, CODE, SCRIPT, and STYLE. If null, the currently configured tags are used.
$codeBlockButtonsstring[]|nullCode block actions to enable, such as copy, ai, and run. If null, the currently configured buttons are used.

Return:

self - Return instance of template view class.

Examples:

// /app/Controllers/Http/DocsController.php

public function onCreate(): void
{
    $this->tpl->htmlMinification(true, ['PRE', 'CODE'], ['copy']);
}

By default, minification and code-block preservation are pre-configured from the environment (env(output.minify.html), env(output.minify.preserve.tags), env(output.minify.codeblock.buttons)) when the view is constructed.


cacheExclude

Exclude one or more templates from caching.

This method allows you to exclude one or more templates name from caching it rendered content.

public final function cacheExclude(array|string $template): self

Parameters:

ParameterTypeDescription
$templatestring|string[]A single template name or an array of template names to ignore from caching.

Return:

self - Return instance of template view class.

Examples:

To disable caching for specific a view templates, example insert and edit will be excluded while allowing cache for other templates.

// /app/Controllers/Http/MainController.php

namespace App\Controllers\Http;

use Luminova\Base\Http\AbstractController;

class MainController extends AbstractController
{
    protected function onCreate(): void
    {
        $this->tpl->cacheExclude(['insert', 'edit']);
    }
}

This can be configured either in your routes/<context>.php file or Controller class.

The recommended approach is within the controller's onCreate or __construct method.


cacheOnly

Specify templates that should be cached exclusively.

This method allows you to explicitly add one or more templates that should only be cached.

Unlike cacheExclude method, the cacheOnly method allows you to specify which view templates should be exclusively cached while others are ignored. This is useful when you want to ensure that only certain views are cache and excluded others entirely.

public final function cacheOnly(array|string $template): self

Parameters:

ParameterTypeDescription
$templatestring|string[]A single template name or an array of template names to allow for caching.

Return:

self - Return instance of template view class.

Examples:

Enable caching for only home, about, and contact views

// /app/Controllers/Http/MainController.php

namespace App\Controllers\Http;

use Luminova\Base\Http\AbstractController;

class MainController extends AbstractController
{
    protected function onCreate(): void 
    {
        $this->tpl->cacheOnly(['home', 'about', 'contact']);
    }
}

Applicable Usage:

If you have 100 views but only want to cache three of them (e.g,home, about, and contact). Using cacheExclude would mean listing all the other 97 views.Instead, use cacheOnly to list just the views you want cached. This way, only those three are cached, and everything else is automatically excluded.


cacheable

Enable or disable view caching globally at the controller or application level.

public final function cacheable(bool $enable = true): self

Parameters:

ParameterTypeDescription
$enableboolWhether to allow view caching.

Return:

self - Return instance of template view class.

If used in a controller’s onCreate() or __construct(), all views under that controller will follow this rule.Useful in api context to manually handle caching.

Examples:

The cacheable method can be called in the controller's onCreate or __construct method.

// /app/Controllers/Http/MainController.php

namespace App\Controllers\Http;

use Luminova\Base\Http\AbstractController;

class MainController extends AbstractController
{
    protected function onCreate(): void
    {
        $this->tpl->cacheable(false);
    }
}

The cacheable method provides a straightforward way to control view caching by setting the caching status globally in a specific controllers, you can ensure that dynamic content remains current without being cached.


cache

Enables view response caching for reuse on future requests.

When called, this method marks the response to be cached. You can optionallyspecify a custom expiration time; otherwise, the default from the .env config will be used.

public final function cache(
    DateTimeInterface|int|null $expiry = null,
    ?bool $immutable = null
): self

Parameters:

ParameterTypeDescription
$expiry\DateTimeInterface|int|nullOptional cache expiration. Accepts:
- DateTimeInterface For specific expiration date/time.
- int For duration in seconds.
- null Use the default expiration from (env(page.cache.expiry)).
$immutablebool|nullSet whether cache content is immutable (default: null).
- true Cached content will not change and can be safely reused.
- false Content may update dynamically.
- null Use default configuration from (env(page.caching.immutable)).

Return:

self - Return instance of template view class.

Examples:

Basic usage with conditional caching.

// /app/Controllers/Http/FooController.php

public function fooView(Luminova\Base\Database\AbstractModel $model): int 
{
    $cache = $this->tpl->cache(60); // Cache for 60 seconds

    if ($cache->expired()) {
        $heavy = $model->doHeavyProcess();

        return $cache->view('foo')
            ->render(['data' => $heavy]);
    }

    return $cache->reuse(); // Reuse the previously cached response
}

burst

Enable template cache burst for a limited duration.

This method temporarily disables browser caching by sending headers that force the client to treat the response as always fresh until removed or the given time or duration expires.

public function burst(DateTimeInterface|int|null $maxTime): self

Parameters:

ParameterTypeDescription
$maxTimeDateTimeInterface|int|nullDuration in seconds or a future time when burst mode should stop.
Set to null to stop bursting.

Return:

self - Returns instance of the view class.

Examples:

public function homepage(): int
{
    return $this->tpl->view('home')
        ->burst(3600)   // Browser will bypass its cache for 1 hour
        ->render(['data' => 'foo']);
}

Using controller view helper method:

public function homepage(): int
{
    // Burst for 5 minutes
    $this->tpl->burst(new DateTime('+5 minutes'));

    // Then render view
    return $this->view('home', ['data' => 'foo']);
}

delete

Deletes the cache entry for the current request view.

public final function delete(?string $version = null): bool

Parameters:

ParameterTypeDescription
$versionstring|nullOptional. Specify the application version to delete (default: null).

Return:

bool - Return true if the cache entry was deleted; false otherwise.


clear

Clears all view cache entries.

public final function clear(?string $version = null): int

Parameters:

ParameterTypeDescription
$versionstring|nullOptional. Specify the application version to clear (default: null).

Return:

int - Return the number of deleted cache entries.

Examples:

Clear all cache entries for the current application version.

$total = $this->tpl->clear();

Clear cache entries for a specific application version.

$total = $this->tpl->clear('1.0.0');

expired

Check if page cache has expired.

Note: the expiration check we use the time used while saving cache.

public final function expired(?string $type = self::HTML): bool

Parameters:

ParameterTypeDescription
$typestring|nullThe view content extension type (default: self::HTML).

Return:

bool - Returns true if cache doesn't exist or expired.

Throws:

Note:

Before calling this method, you must first call cache method instantiate it for use.

For the expiration check, we use the expiration set in env while saving cache, also don't worry about the cache key as it handled internally to save your precious time.


reuse

Reuse previously cached view content if available.

public final function reuse(): int

Return:

int - Returns one of the following status codes:

  • STATUS_SUCCESS if cache was found and successfully reused,
  • STATUS_SILENCE if no valid cache was found — silent exit, allowing manual fallback logic.

Throws:

Examples:

public function homepage(Luminova\Base\Database\AbstractModel $model): int
{
    // Enable caching for 2 minutes
    $this->tpl->cache(120); 

    if ($this->tpl->reuse() === STATUS_SUCCESS) {
        // Cache hit, response already sent
        return STATUS_SUCCESS; 
    }

    $data = $model->getHomepageData();

    return $this->tpl->view('home')
        ->render(['data' => $data]);
}

onExpired

Conditionally renew cached view if expired, otherwise reuse it.

public final function onExpired(
    Closure $onRenew,
    array $options = [],
    ?string $type = self::HTML
): int

Parameters:

ParameterTypeDescription
$onRenew\ClosureCallback to execute if cache has expired. Should return STATUS_SUCCESS or STATUS_SILENCE.
$optionsarray<array-key, mixed>Optional options to pass to the $onRenew callback argument.
$typestring|nullType of content to check cache for, (e.g. View::HTML, View::JSON).

Return:

int - Return the status code:

  • Status code from reuse() if a valid, non-expired cache is available,
  • Otherwise, status code returned by the $onRenew callback.

Examples:

public function books(): int 
{
    return $this->tpl->cache(300)
        ->onExpired(function(array $options): int {
                return $this->view('books', [
                    'books' => Book::find($options['group'])
                ]);
            }, 
            ['group' => 'programming'] 
        );
}

redirect

Redirect to a different URI or route.

public final function redirect(string $uri, int $status = 302): never

Parameters:

ParameterTypeDescription
$uristringThe target URI or route.
$statusintThe HTTP redirect status code (default: 302).

Examples:

$this->tpl->redirect('/dashboard');   // absolute path
$this->tpl->redirect('user/profile'); // relative path

Generate a relative URI from the public root.

Builds a path to routes or public assets (CSS, JS, images) relative to the current request.

  • In production, always returns a root-based path.
  • In development, calculates a relative path using URI depth.
public final function link(string $route = '/'): string

Parameters:

ParameterTypeDescription
$routestringOptional route or asset path to append (default: /).

Return:

string - Relative or root-based URI.

Examples:

<link href="<?= $this->link('assets/css/main.css') ?>" rel="stylesheet">
<a href="<?= $this->link('about') ?>">About Us</a>

title

Return the current view's formatted page title.

Converts underscores, dashes, hyphens, and commas in the active template name to spaces, capitalizes each word, and appends a suffix.

public final function title(?string $suffix = null): string

Parameters:

ParameterTypeDescription
$suffixstring|nullSuffix appended to the title. If null (default), appends " - " . APP_NAME. Pass an empty string to omit any suffix, or a custom string to override it.

Return:

string - The formatted page title.

Examples:

<title><?= $this->title() ?></title> 
<!-- "Dashboard - My App" -->

<title><?= $this->title(' | My App') ?></title>
<!-- "Dashboard | My App" -->

<title><?= $this->title('') ?></title>
<!-- "Dashboard" -->

hasOption

Checks if a given name exists as a view option.

Useful for determining whether a value was set in the current view context via configuration options.

public final function hasOption(string $name): bool

Parameters:

ParameterTypeDescription
$namestringThe option name to check.

Return:

bool - Returns true if the option exists, otherwise false.


isExported

Checks if a given property exists as an exported alias.

Useful for determining whether a value was made available to thecurrent view via the export() method.

public final function isExported(string $name): bool

Parameters:

ParameterTypeDescription
$namestringThe export name or alias to check.

Return:

bool - Returns true if the export exists, otherwise false.


isTemplate

Check if the current view file matches one or more template names.

Accepts a single template name or an array of names and returns true if the active template filename is an exact match.

public final function isTemplate(string|array $template): bool

Parameters:

ParameterTypeDescription
$templatestring|arrayOne or more template filenames to compare against.

Return:

bool - Returns true if the current template matches; otherwise false.

Examples:

<nav>
    <a href="about" <?= $this->isTemplate('about') ? ' class="active"' : ''; ?>>About Us</a>
</nav>

inTemplate

Return a value or run a callback only when the current template matches.

When the given template name matches the active template:

  • If $value is callable, it is executed and its return value is used.
  • Otherwise, $value is returned as-is.

When the template does not match:

  • The $default value is used instead (callable or scalar).
public function inTemplate(string|array $template, mixed $value, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$templatestring|arrayTemplate name(s) to match against.
$valuecallable(View $view):mixed|scalarValue or callback used when matched.
$defaultcallable(View $view):mixed|scalarValue or callback used when not matched.

Return:

mixed - Returns the evaluated result from $value or $default.

Examples:

<a href="about" <?= $this->inTemplate('about', 'class="active"', ''); ?>>About Us</a>

This example shows how you can use inTemplate to mark active nav link without using JavaScript:

<?php
// /resources/Views/layouts/header.nav.php
$states = ['class="active"', ''];
?>

<nav>
    <a href="about" <?= $this->inTemplate('about', ...$states); ?>>About Us</a>
    <a href="service" <?= $this->inTemplate(['service', 'services'], ...$states); ?>>Our Service</a>
</nav>

getExport

Retrieves a property exported from the application context.

public final function getExport(string $name): mixed

Parameters:

ParameterTypeDescription
$namestringThe export property class name or alias used when exporting.

Return:

mixed|null - Return the export value, or null if not found.


getOption

Retrieves a value from the view's context options.

If the key does not exist, the method also checks for the same key prefixed with _to support backward compatibility when $variablePrefixing is not null.

public final function getOption(string $key): mixed

Parameters:

ParameterTypeDescription
$keystringThe option name.

Return:

mixed|null - Returns the option value if set; otherwise, checks for the key prefixed with _ and returns that value if found. Returns null if neither exists.

Note:

Supports fallback to prefixed keys for flexibility and backward compatibility.


getExports

Returns all exported application properties available to the view.

public final function getExports(): array

Return:

array<string,mixed> - Return an associative array of exported properties.


getOptions

Returns all view context options extracted for the view.

public final function getOptions(): array

Return:

array<string,mixed> - Return an associative array of view context options.


getTemplate

Get the template filename.

By default, returns the resolved template name (which may differ from the originalif a fallback like 404 was used).

Pass false to get the original template name exactly as specified in the controller.

public final function getTemplate(bool $resolved = true): string

Parameters:

ParameterTypeDescription
$resolvedboolWhether to return the resolved filename (true) or the original (false).

Return:

string - Return the current view template file basename.


getStatusCode

Get the current HTTP status code.

Useful when you need to access the same status code that was used to render the template directly from inside the template itself.

public final function getStatusCode(): int

Return:

int - Return the HTTP status code (e.g., 200, 404, 500).