← Documentation

API Reference

This document provides the complete API reference for the Zandy_Template template engine.

Table of Contents

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
): string

Parameters

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

Parameters

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
): void

Parameters

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
): mixed

Parameters

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): array

Parameters

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): array

Parameters

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

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): ?int

Parameters

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 throws Zandy_Template_RuntimeException — with templateFile / templateLine properties and a "(template line N)" message prefix; the original exception stays in getPrevious().

getTemplateVars()

Safely extracts template variables (used with the outCache + include approach)

Syntax

public static function getTemplateVars(array|null $explicitVars = null): array

Parameters

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

Parameters

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

Parameters

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

Parameters

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): bool

Parameters

Return Value and Failure Contract

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 inside

Cache 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'
): void

Parameters

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

Parameters

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): void

Parameters

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): void

Parameters

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(): bool

Return 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(): bool

Parameters

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:

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