API Reference
This document provides the complete API reference for the Zandy_Template template engine.
Table of Contents
- outString()
- outCache()
- includeTemplate()
- includeCompiledWithVars()
- validate()
- validateDetailed()
- getRegisteredDirectives() / getRegisteredFunctions() / getRegisteredValidators()
- mapCompiledLine()
- getTemplateVars()
- out()
- outHTML()
- outEval()
- check_syntax()
- Plugin System
- Cache Mode Constants
outString()
Returns the HTML string after data has been populated (recommended)
Syntax
public static function outString(
string $tplFileName,
string $tplDir = '',
string $cacheDir = '',
bool $forceRefreshCache = false,
array|null $vars = null
): stringParameters
$tplFileName(string) - Template file name$tplDir(string) - Template directory (optional, defaults to$GLOBALS['siteConf']['tplDir'])$cacheDir(string) - Cache directory (optional, defaults to$GLOBALS['siteConf']['tplCacheBaseDir'])$forceRefreshCache(bool) - Whether to force a cache refresh (default false)$vars(array|null) - Explicitly passed variable array (optional; if provided, only these variables are used)
Return Value
Returns the HTML string after data has been populated.
Usage Example
// Option 1: use global variables (backward compatible)
$GLOBALS['user'] = $user;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);
echo $html;
// Option 2: pass variables explicitly (recommended, safer)
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
'user' => $user,
'data' => $data
]);
echo $html;
// Option 3: configure whitelist mode
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data'];
$GLOBALS['user'] = $user;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);outCache()
Returns the path of the compiled cache file, which you then include
Syntax
public static function outCache(
string $tplFileName,
string $tplDir = '',
string $cacheDir = '',
bool $forceRefreshCache = false
): string|falseParameters
$tplFileName(string) - Template file name$tplDir(string) - Template directory (optional)$cacheDir(string) - Cache directory (optional)$forceRefreshCache(bool) - Whether to force a cache refresh (default false)
Return Value
Returns the path of the compiled cache file, or false on failure.
Usage Example
// Option 1: use includeTemplate() (recommended, supports safe mode)
Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir, false, ['user' => $user]);
// Option 2: include manually (variables must be handled manually)
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract(Zandy_Template::getTemplateVars(['user' => $user]));
include $cacheFile;
// Option 3: use global variables (backward compatible, but not recommended)
$GLOBALS['user'] = $user;
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract($GLOBALS); // ⚠️ security risk
include $cacheFile;includeTemplate()
Safely includes the template file (recommended for the outCache approach)
Syntax
public static function includeTemplate(
string $tplFileName,
string $tplDir = '',
string $cacheDir = '',
bool $forceRefreshCache = false,
array|null $vars = null
): voidParameters
$tplFileName(string) - Template file name$tplDir(string) - Template directory (optional)$cacheDir(string) - Cache directory (optional)$forceRefreshCache(bool) - Whether to force a cache refresh (default false)$vars(array|null) - Explicitly passed variable array (optional)
Return Value
No return value; the template content is output directly.
Usage Example
// Option 1: use global variables (backward compatible)
$GLOBALS['user'] = $user;
Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir);
// Option 2: pass variables explicitly (recommended, safer)
Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir, false, ['user' => $user]);
// Option 3: configure whitelist mode
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data'];
$GLOBALS['user'] = $user;
Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir);includeCompiledWithVars()
Includes a compiled artifact with an explicit variable set (v1.12.0, the runtime support for passing arguments via the template with= attribute)
Syntax
public static function includeCompiledWithVars(
string $compiledFile,
array $vars
): mixedParameters
$compiledFile(string) - Path to the compiled artifact (usually the return value of outCache)$vars(array) - Variable set (extracted into an isolated scope before include)
Return Value
The include return value (false on failure).
Notes
Includes after extracting into an isolated scope (EXTR_SKIP protects this method's parameter names)— the passed variables do not leak into the caller's scope. The template directive's with=/only is built on top of this method; it is generally used for scenarios needing "explicit vars + isolated inclusion".
validate()
Structural diagnostics (non-fatal): collects all template structure errors and returns an array of messages.
Syntax
public static function validate(string $template): arrayParameters
$template(string) - template source
Return value
array - diagnostic messages (empty array for valid templates)
Example
$diags = Zandy_Template::validate($tpl);
foreach ($diags as $msg) {
echo $msg, "\n";
}validateDetailed()
Structured structural diagnostics (v1.13.0): adds an error code, line number, fix suggestion and source snippet to each diagnostic from validate() — ready for IDE plugins and CI integration.
Syntax
public static function validateDetailed(string $template): arrayParameters
$template(string) - template source
Return value
array - diagnostic entries with fields:
| Field | Type | Description |
|---|---|---|
code |
string | Error code (table below) |
level |
string | error |
line |
int | Template line number (0 when not extractable) |
message |
string | Original diagnostic message (same as validate()) |
suggestion |
string | Fix suggestion |
snippet |
string | Source line snippet (truncated at 160 chars + …) |
Error codes:
| Code | Meaning |
|---|---|
| ZTE101 | Unclosed block |
| ZTE102 | Unexpected close |
| ZTE103 | Interleaved nesting |
| ZTE104 | Branch placement (elseif/else/duplicate else) |
| ZTE105 | Loop empty-state attachment |
| ZTE106 | switch child placement |
| ZTE107 | Duplicate default |
| ZTE100 | Other structural error |
Example
foreach (Zandy_Template::validateDetailed($tpl) as $d) {
printf("[%s] line %d: %s\n suggestion: %s\n", $d['code'], $d['line'], $d['message'], $d['suggestion']);
}getRegisteredDirectives() / getRegisteredFunctions() / getRegisteredValidators()
Extension-protocol introspection APIs (v1.11.0): read the plugin tables registered in the current process — for plugin listings, debugging and host integration.
Syntax
public static function getRegisteredDirectives(): array // array('before'=>[name=>handler], 'after'=>[...])
public static function getRegisteredFunctions(): array // same shape
public static function getRegisteredValidators(): array // array(callable, ...)Return value
- Directives/filters:
array('before' => array(name => handler), 'after' => array(...)) - Validators: list of callables in registration order
Protocol version constant
Zandy_Template::ZTE_EXTENSION_PROTOCOL_VERSION; // '1.0'Example
foreach (array_keys(Zandy_Template::getRegisteredFunctions()['after']) as $name) {
echo $name, "\n"; // upper / lower / escape / ...
}mapCompiledLine()
Compiled line → template line (v1.14.0 runtime error locating)
Syntax
public static function mapCompiledLine(int $compiledLine, array|null $sourceMap = null): ?intParameters
$compiledLine(int) - compiled artifact line (as found in an exception stack trace)$sourceMap(array|null) - mapping table (defaults to the latest compile's source map)
Return value
int|null - template line; null when unmapped (falls back to the nearest earlier mapped line)
Example
try {
Zandy_Template::outString('page.htm', $tplDir, $cacheDir);
} catch (Throwable $e) {
$tplLine = Zandy_Template::mapCompiledLine($e->getLine());
echo "Template line ", var_export($tplLine, true), ": ", $e->getMessage();
}Automatic mode: with
siteConf['tpl_error_map'] = true(PHP 7+), outString performs the mapping itself and throwsZandy_Template_RuntimeException— withtemplateFile/templateLineproperties and a "(template line N)" message prefix; the original exception stays ingetPrevious().
getTemplateVars()
Safely extracts template variables (used with the outCache + include approach)
Syntax
public static function getTemplateVars(array|null $explicitVars = null): arrayParameters
$explicitVars(array|null) - Explicitly passed variable array (optional)
Return Value
Returns the extracted variable array.
Usage Example
// Option 1: pass variables explicitly (recommended)
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract(Zandy_Template::getTemplateVars(['user' => $user]));
include $cacheFile;
// Option 2: use the configured mode
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data'];
$GLOBALS['user'] = $user;
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract(Zandy_Template::getTemplateVars()); // uses the configured whitelist
include $cacheFile;out()
General-purpose output method with a selectable output mode
Syntax
public static function out(
string $tplFileName,
string $tplDir = '',
string $cacheDir = '',
bool $forceRefreshCache = false,
int $cacheMod = ZANDY_TEMPLATE_CACHE_MOD_PHPC
): string|falseParameters
$tplFileName(string) - Template file name$tplDir(string) - Template directory (optional)$cacheDir(string) - Cache directory (optional)$forceRefreshCache(bool) - Whether to force a cache refresh (default false)$cacheMod(int) - Cache mode (see the constant descriptions below)
Return Value
The return value depends on the cache mode (see the cache mode constant descriptions).
Usage Example
// Return HTML content
$html = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_HTML_CONTENTS);
// Return the cache file path
$cacheFile = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_PHPC);
// Return an eval-able string
$code = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_EVAL);
eval($code);outHTML()
Returns the HTML file path or content
Syntax
public static function outHTML(
string $tplFileName,
string $tplDir = '',
string $cacheDir = '',
bool $forceRefreshCache = false,
int $outMod = ZANDY_TEMPLATE_CACHE_MOD_HTML,
array|null $vars = null
): string|falseParameters
$tplFileName(string) - Template file name$tplDir(string) - Template directory (optional, falls back tositeConf['tplDir']; only a non-empty string counts as valid)$cacheDir(string) - Cache directory (optional; only a non-empty string counts as a valid directory, with or without a trailing slash; when omitted it falls back in order:siteConf['cacheHTMLDir']→siteConf['tplCacheBaseDir'])$forceRefreshCache(bool) - Whether to force a cache refresh (default false)$outMod(int) - Output mode (see the cache mode constants)$vars(array|null) - Explicitly passed variable array (optional)
Return Value
Returns the HTML file path or content, depending on the output mode.
Usage Example
// Return the HTML file path
$htmlFile = Zandy_Template::outHTML('template.htm', $tplDir, $cacheDir);
// Return HTML content
$htmlContent = Zandy_Template::outHTML('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_HTML_CONTENTS);outEval()
Returns an eval-able string
Syntax
public static function outEval(string $tplFileName, string $tplDir = ''): string|falseParameters
$tplFileName(string) - Template file name$tplDir(string) - Template directory (optional)
Return Value
Returns an eval-able string, or false on failure.
Usage Example
$code = Zandy_Template::outEval('template.htm', $tplDir);
if ($code !== false) {
ob_start();
eval($code);
$result = ob_get_clean();
echo $result;
}check_syntax()
Checks whether a compiled artifact (PHP file) is syntactically valid
Syntax
public static function check_syntax(string $filename, string $tplName = '', bool $unlinkOnFailure = false): boolParameters
$filename(string) - Path of the PHP file to check$tplName(string) - Template name (optional, used in error messages)$unlinkOnFailure(bool) - Delete the checked file before halt on syntax error (used by the internal compile pipeline)
Return Value and Failure Contract
- Valid syntax: returns
true - Syntax error: does NOT return an error string — follows the engine's unified
failure contract:
halt()(renders an error page andexit(255)). Callers cannot obtain error details via the return value; full diagnostics (path, failing line context) are written to error_log
Usage Example
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
$result = Zandy_Template::check_syntax($cacheFile, 'template.htm');
// Reaching this line means the syntax is valid ($result === true);
// a syntax error would have halted insideCache Mode Constants
ZANDY_TEMPLATE_CACHE_MOD_PHPC (1)
Returns the path of the compiled PHP file
$cacheFile = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_PHPC);
include $cacheFile;ZANDY_TEMPLATE_CACHE_MOD_HTML (2)
Returns the HTML file path
$htmlFile = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_HTML);ZANDY_TEMPLATE_CACHE_MOD_EVAL (4)
Returns an eval-able string
$code = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_EVAL);
eval($code);ZANDY_TEMPLATE_CACHE_MOD_HTML_CONTENTS (8)
Returns HTML content
$html = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_HTML_CONTENTS);
echo $html;Plugin System
registerDirective()
Registers a custom directive plugin
Syntax
public static function registerDirective(
string $name,
callable $handler,
string $position = 'after'
): voidParameters
$name(string) - Directive name (such aswhen,custom-loop); must not clash with a built-in directive (conflicting registrations are rejected with a warning)$handler(callable) - Handler function receiving:($content, $params, $context)—for block syntax$contentis the block content, for single-line syntax it is an empty string;$contextis a context array containingtplDir(template directory),cacheDir(cache directory),EOB(heredoc end identifier), andtplFileName(template file name)$position(string) - Execution position:'before'(before core features, operates on the template source) or'after'(after core features, operates on the compiled output, the default)
Return Value
No return value.
Usage Example
// Register a custom directive (single-line syntax, see the `when` implementation in examples/plugin_demo.php)
Zandy_Template::registerDirective('when', function($content, $params, $context) {
$EOB = $context['EOB'];
// $params is the argument part of the opening tag (e.g. "$user->isAdmin()")
// Mirrors the built-in if: close the current heredoc, then open the if block
return "\r\n$EOB;\r\nif ($params) {echo <<<$EOB\r\n";
}, 'after');
// Use the custom directive
// Template: <!--{when $user->isAdmin()}-->registerFunction()
Registers a custom function plugin (filter)
Syntax
public static function registerFunction(
string $name,
callable $handler,
string $position = 'after'
): voidParameters
$name(string) - Function name (such asupper,escape,truncate)$handler(callable) - Handler function receiving:($value, $params = '')and returning a PHP code string$position(string) - Execution position:'before'(before core features) or'after'(after core features, the default)
Return Value
No return value.
Usage Example
// Register a custom filter
Zandy_Template::registerFunction('upper', function($value, $params = '') {
return "strtoupper($value)";
}, 'after');
// Use the custom filter
// Template: {$var|upper}registerValidator()
Registers a plugin validation callback (used to validate directive structural integrity)
Syntax
public static function registerValidator(callable $validator): voidParameters
$validator(callable) - Validation function receiving:($template); if validation fails it should callZandy_Template::halt()
Return Value
No return value.
Usage Example
// Register a validation callback
Zandy_Template::registerValidator(function($template) {
// Check the when/else-when/end-when structure
$whenCount = preg_match_all('/<!--\{when\s+/i', $template);
$endWhenCount = preg_match_all('/<!--\{end-when\}/i', $template);
if ($whenCount !== $endWhenCount) {
Zandy_Template::halt('Incomplete when directive structure: the number of when and end-when does not match', true);
}
});setValidationEnabled()
Sets whether directive structure validation is enabled
Syntax
public static function setValidationEnabled(bool $enable): voidParameters
$enable(bool) - Whether to enable validation (true enables, false disables)
Return Value
No return value.
Usage Example
// Enable validation (default)
Zandy_Template::setValidationEnabled(true);
// Disable validation (can be turned off in production to improve performance)
Zandy_Template::setValidationEnabled(false);isValidationEnabled()
Gets the current validation state
Syntax
public static function isValidationEnabled(): boolReturn Value
Returns whether validation is currently enabled (true enabled, false disabled).
Usage Example
$isEnabled = Zandy_Template::isValidationEnabled();
if ($isEnabled) {
echo "Validation is enabled";
}loadBuiltinPlugins()
Loads the built-in plugins
Syntax
public static function loadBuiltinPlugins(): boolParameters
No parameters.
Return Value
bool—true if the plugin files exist and were loaded successfully, otherwise false.
Usage Example
// Load all built-in plugins
require_once 'plugins/builtin.php';
// Or
Zandy_Template::loadBuiltinPlugins();Built-in plugins include:
custom-loop- Custom loop directivewhen/else-when/end-when- Conditional directivesdate-format- Date formatting filterdebug-info- Debug information filterfilters- Common filters (upper, lower, escape, truncate, default, nl2br, date)
Static API Retirement Timeline (from v1.9)
| Phase | Version | Status |
|---|---|---|
| Coexistence begins | v1.9.0 | Instantiated API goes live (Zandy_Template_Engine), all static APIs retained |
| Deprecation marking | Landed early in v1.9.0, effective from v1.10 | Docblocks of static compile/render entry points marked @deprecated (visible to IDEs/static analysis, not removed, no runtime change) |
| Removal | v2.0.0 | Static entry points deleted (gated by criteria: instantiated API has run stably long enough + removal is deemed necessary) |
Marked entry points: parse / out / outCache / outString / outHTML / outEval / includeTemplate / getTemplateVars / loadBuiltinPlugins / check_syntax. See the instantiated API section of syntax.md for migration.
More Information
- Usage Guide - Detailed usage instructions and best practices
- Syntax Reference - Complete template syntax
- Security Guide - Secure usage guide
- Plugin Development Guide - Detailed plugin development instructions