PHP Luminova: View Template Rendering
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
- Fast Rendering – Compiles and minifies templates automatically.
- Flexible Output – Supports templates that return HTML, arrays, objects, or scalars.
- Built-in Caching – Saves rendered templates for better performance.
- 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:
$thisin Global Mode – Refers to the current view class instance. You can access view methods and application properties directly.$selfin Isolation Mode – Refers to an instance ofLuminova\Template\Engines\Scope, which safely exposes only allowed view properties and the application object.
Note:Accessing
$selfin non-isolation mode will throw aRuntimeException.It is also recommended not to override$selfinside 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.
Links
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 hereThis 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
selfas an option name, sinceselfis 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()andgetOptions().
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;
// htmlTemplate 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:
| Type | Output Handling |
|---|---|
Scalar (string, int, float, bool) | Converted to string and sent directly. |
| SimpleXMLElement | Converted to XML via asXML() with Content-Type: application/xml. |
| DOMDocument | Converted to XML via saveXML() with Content-Type: application/xml. |
| Stringable Object | Converted to string via casting to (string) and sent. |
| Callable | Executed, 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
arraysorobjects(without__toString()/toString()) automatically produces JSON output to the client. Returningscalars,Stringableobjects, orXMLtypes are rendered according to their type. Callables are executed before output.Any other content type (e.g. a resource) is unsupported and throws aRuntimeException.
---*
Class Definition
- Full namespace:
Luminova\Template\View - This class implements Luminova\Interface\LazyObjectInterface.
- This class is final.
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
| Constant | Type | Value | Description |
|---|---|---|---|
HTML | string | 'html' | HTML templates or content. |
XHTML | string | 'xhtml' | Strict XHTML templates or content. |
JSON | string | 'json' | JSON-formatted content. |
TEXT | string | 'txt' | Plain text content. |
XML | string | 'xml' | XML-formatted content. |
JS | string | 'js' | JavaScript files or code blocks. |
CSS | string | 'css' | CSS stylesheets or inline styles. |
RDF | string | 'rdf' | RDF-formatted content for semantic data. |
ATOM | string | 'atom' | ATOM feed format. |
RSS | string | 'rss' | RSS feed format. |
BIN | string | 'bin' | Binary string content format. |
PNG | string | 'png' | PNG images. |
JPEG | string | 'jpeg' | JPEG images. |
GIF | string | 'gif' | GIF images. |
WEBP | string | 'webp' | WebP images. |
SVG | string | 'svg' | SVG images. |
AVIF | string | 'avif' | AVIF images. |
MP3 | string | 'mp3' | MP3 audio. |
OGG | string | 'ogg' | OGG audio. |
WEBM | string | 'webm' | WebM audio or video format. |
MP4 | string | 'mp4' | MP4 video. |
Note:
They are not the same as HTTP header
Content-Typevalues, 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 forView::TEXTwhen callingview().
WEBMnote: Must be served with the correct header (audio/webmorvideo/webm) viaheader(), 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
exportfor 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
nullfor 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:
| Parameter | Type | Description |
|---|---|---|
$app | Application|LazyObjectInterface|null | Optional 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\AbstractApplicationclass, which can be accessed inside controller classes.For global helper access, useLuminova\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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$app | AbstractApplication&LazyObjectInterface | The application object, or a lazy-loaded application object. |
Return:
self - Return instance of template view class.
Throws:
- Luminova\Exceptions\RuntimeException - If
$appis not an instance ofApplication.
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
$templatemust exclude file extensions (.php,.tpl,.twg, etc).For unsupported types, useresponse(...)->render(...)for manual handling.
public final function view(string $template, string $type = self::HTML): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$template | string | View filename without extension (e.g., dashboard, index). |
$type | string | The template content type (default: View::HTML). |
Return:
self - Return instance of template view class.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If
$templateis empty, or$typeis not a supported view type.
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): intParameters:
| Parameter | Type | Description |
|---|---|---|
$options | array<string, mixed> | Additional parameters to pass in the template (available inside view). |
$status | int | The HTTP status code (default: 200 OK). |
Return:
int - Return one of the following status codes:
STATUS_SUCCESSif the view is handled successfully,STATUS_SILENCEif failed, silently terminate without error page allowing you to manually handle the state.
Throws:
- Luminova\Exceptions\RuntimeException - If the view rendering fails.
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): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$options | array<string, mixed> | Additional parameters to pass in the template (available inside view). |
$status | int | HTTP status code (default: 200 OK). |
Return:
string|null - Return the compiled view contents or null if no content.
Throws:
- Luminova\Exceptions\RuntimeException - If the view rendering fails.
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): PromiseInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$options | array<string, mixed> | Additional parameters to pass in the template (available inside view). |
$status | int | HTTP 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(): boolReturn:
bool - Return true if the resolved template matches the requested template name and the file exists on disk, false otherwise.
Note:Returns
falsewhen the resolved filename differs from the requested template (for example, when production mode silently falls back to the4xxerror 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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string|null | Optional 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.
| Key | Type | Description |
|---|---|---|
location | string | Resolved file path. |
type | string | View content type. |
template | string | Selected template name. |
engine | string | Template engine name. |
size | int\|false | File size in bytes, or zero before a file is resolved. |
timestamp | int\|false | Last modification time, or zero before a file is resolved. |
modified | string | Formatted modification date, or an empty string. |
module | string\|null | HMVC module name when available. |
dirname | string\|null | Template directory when available. |
extension | string\|null | Template file extension. |
filename | string\|null | Template 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
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$target | object|string | The class name, object instance to expose. |
$alias | string|null | Optional alias for reference (Defaults to class class/object name). |
$shared | bool | If true and $target is class name, the same instance will be reused. |
Return:
bool - Returns true if imported, otherwise throw error.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If
$targetor$aliasis an empty string. - Luminova\Exceptions\RuntimeException - If the alias already exists.
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
$targetis 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The template response header key. |
$value | mixed | The 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$headers | array<string, mixed> | Associative array of headers key-pair. |
Return:
self - Return instance of template view class.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If a non-empty list array is provided instead of an associative array.
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(): arrayReturn:
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 = '/'): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$module | string | Named 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:
- Luminova\Exceptions\RuntimeException - If the resulting module name is empty or contains a path separator. Omitting the argument also throws because the declared default is
'/'.
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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$controller | string | Fully 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\Controllerand 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$folder | string | Subfolder name to look for views. |
Return:
self - Return instance of template view class.
Notes:
- When used in a controller's
onCreateor__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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$depth | int|null | Number 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/fooNormally, accessing
https://example.com/app/accountwould trigger auto-detection of../../in development environment likeXAMPPdue to the URI depth (public/app/account).But since we explicitly set the depth to1, 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
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$enable | bool | Whether to minify the template content. |
$preserveTags | string[]|null | HTML tags whose content should be preserved, such as PRE, CODE, SCRIPT, and STYLE. If null, the currently configured tags are used. |
$codeBlockButtons | string[]|null | Code 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$template | string|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
onCreateor__constructmethod.
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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$template | string|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
100views but only want to cache three of them (e.g,home,about, andcontact). UsingcacheExcludewould mean listing all the other97views.Instead, usecacheOnlyto 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$enable | bool | Whether 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
cacheablemethod 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
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$expiry | \DateTimeInterface|int|null | Optional cache expiration. Accepts: - DateTimeInterface For specific expiration date/time.- int For duration in seconds.- null Use the default expiration from (env(page.cache.expiry)). |
$immutable | bool|null | Set 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$maxTime | DateTimeInterface|int|null | Duration 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$version | string|null | Optional. 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): intParameters:
| Parameter | Type | Description |
|---|---|---|
$version | string|null | Optional. 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$type | string|null | The view content extension type (default: self::HTML). |
Return:
bool - Returns true if cache doesn't exist or expired.
Throws:
- Luminova\Exceptions\RuntimeException - Throw if the cached version doesn't match with the current view type.
Note:
Before calling this method, you must first call
cachemethod instantiate it for use.For the expiration check, we use the expiration set in
envwhile 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(): intReturn:
int - Returns one of the following status codes:
STATUS_SUCCESSif cache was found and successfully reused,STATUS_SILENCEif no valid cache was found — silent exit, allowing manual fallback logic.
Throws:
- Luminova\Exceptions\RuntimeException - If called without first calling
cache()method.
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
): intParameters:
| Parameter | Type | Description |
|---|---|---|
$onRenew | \Closure | Callback to execute if cache has expired. Should return STATUS_SUCCESS or STATUS_SILENCE. |
$options | array<array-key, mixed> | Optional options to pass to the $onRenew callback argument. |
$type | string|null | Type 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
$onRenewcallback.
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): neverParameters:
| Parameter | Type | Description |
|---|---|---|
$uri | string | The target URI or route. |
$status | int | The HTTP redirect status code (default: 302). |
Examples:
$this->tpl->redirect('/dashboard'); // absolute path
$this->tpl->redirect('user/profile'); // relative pathlink
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 = '/'): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$route | string | Optional 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$suffix | string|null | Suffix 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$template | string|array | One 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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$template | string|array | Template name(s) to match against. |
$value | callable(View $view):mixed|scalar | Value or callback used when matched. |
$default | callable(View $view):mixed|scalar | Value 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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The 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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The 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(): arrayReturn:
array<string,mixed> - Return an associative array of exported properties.
getOptions
Returns all view context options extracted for the view.
public final function getOptions(): arrayReturn:
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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$resolved | bool | Whether 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(): intReturn:
int - Return the HTTP status code (e.g., 200, 404, 500).