Usage Guide
This document provides a detailed usage guide for the Zandy_Template template engine.
Table of Contents
Installation and Configuration
Installation
Option 1: Using Composer (recommended)
composer require zandy/php-template-engineNote:
- Composer 2.x itself requires PHP 7.2.5+; if your project uses PHP 5.6 - 7.2.4, use Composer 1.x or the manual installation method
- The template engine itself supports PHP 5.6 - 8.6
Option 2: Manual installation
- Download the
Template.phpfile require_once 'Template.php'in your code- To use plugins,
require_oncethe corresponding plugin files manually
Basic Configuration
Delimiter Configuration
The 4 delimiter constants (
ZANDY_TEMPLATE_DELIMITER_LOGIC_LEFT/RIGHT,VAR_LEFT/RIGHT) can be pre-defined before requiring the engine — square brackets, braces,[% %], any reasonable combination with automatic lexical disambiguation. See "Delimiter Configuration" in syntax.en.md. Defaults require no configuration.
The $GLOBALS['siteConf'] configuration must be set:
$GLOBALS['siteConf'] = array(
'tplBaseDir' => '/path/to/templates/base', // template base directory
'tplCacheBaseDir' => '/path/to/cache', // cache base directory (HTML cache is also written here by default; with or without a trailing slash)
'cacheHTMLDir' => '/path/to/cache/html', // optional: dedicated directory for HTML cache, falls back to tplCacheBaseDir when unset
'tplDir' => '/path/to/templates', // current template directory
);Configuration Reference
tplBaseDir- Template base directory, used for path validationtplCacheBaseDir- Cache base directory, used for path validation (HTML cache is also written here by default; with or without a trailing slash)cacheHTMLDir- Optional, dedicated directory for HTML cache (only a non-empty string counts as a valid setting; falls back totplCacheBaseDirwhen unset)tplDir- Current template directory, the lookup path for template filestplCacheMaxTime- Cache expiry time (seconds), 3 hours by defaulttpl_lock_timeout- Optional, total wait timeout for the compile lock (seconds), 30 by default. When the lock holder is stuck (debugger freeze,php -lhang, NFS stall), waiters degrade to lock-free compilation after the timeout and emit anerror_logwarning instead of queueing forevertpl_include_max_depth- Optional, maximum nesting depth oftemplatedirective includes, 32 by default. Exceeding the limit or detecting an include cycle (the same template reappearing in the include stack) halts with a clear diagnostic instead of recursing until memory is exhaustedcontentIntegrityCheck- Optional, compiled cache content integrity check (off by default). Once enabled, the md5 of the template content is embedded in the header of the compiled artifact (ZTE-TPL-MD5), and on a hit a content comparison replaces the mtime comparison: scenarios such as a rolled-back/lost template mtime or same-second precision boundaries are all immune, any content change always triggers recompilation and unchanged content is never falsely invalidated. Overhead is about 34µs per request (measured with a 15KB template); once enabled, old-format cache entries (without a check header) are automatically invalidated and recompiled to fill the gap. The constantdefine('TPL_CONTENT_INTEGRITY_CHECK', true)can also be usedalarmEmailThrottle- Optional, throttle window for alarm emails (seconds), 300 by default, set to 0 to disable throttling (introduced in v1.10.0). When a severe error triggers an alarm email, only one email is sent per error signature (md5 of the message body) within the window, preventing alarm-channel bombardment during bulk upgrades or broken-template incidents; the severity gating (only severe errors send mail) is unaffected by this keytpl_debug_full- Optional, capability gate for thefull/allarguments of the<!--{debug-info}-->directive (boolean, off by default, introduced in v1.7.1).tpl_debugmust also be enabled for any output; when this key is off, full/all degrade to basic info (variable dumps and call stacks are not emitted)tpl_cache_host_whitelist- Optional, host segment whitelist for compiled cache directories (array of strings, introduced in v1.14.0). When configured, compiled artifacts for hosts in the list (case-insensitive) are stored in their own<tplCacheBaseDir>/ztec/<host>/segment, everything else goes toztec/default/; when unset,ztec/default/is used as well (host isolation is handled by the md5 salt of the cache key — random Host headers no longer create new directories). When thePROJECT_NAMEconstant is defined, segmentation follows the project name and takes precedence over this keytplRequireBaseDir- Optional, path-boundary strictness switch (boolean, off by default, introduced in v1.15.0). When true, outHTML/outEval refuse to render iftplBaseDiris not configured (fail-closed, aligning with the outCache contract); when off, the historical pass-through is kept with a one-time error_log notice. Recommended once your deployment is ready. See "Template root boundary" in security.en.mdforceRefreshCache- Optional, global force-refresh switch (boolean, off by default, present since the first engine release). When true, all outCache/outHTML calls behave as force-refresh (equivalent to passing forceRefreshCache=true on every call, no per-call-site changes); the constantTPL_FORCE_CACHEenables it equivalently. Typical use: CI warm-up verification, full recompilation during release windows; merged under the concurrent compile lock when actually waited (v1.14.0)
Quick Start
Basic Usage
// If using Composer
require_once 'vendor/autoload.php';
// If installed manually
require_once 'Template.php';
// Configuration
$GLOBALS['siteConf'] = array(
'tplBaseDir' => '/path/to/templates/base',
'tplCacheBaseDir' => '/path/to/cache',
'tplDir' => '/path/to/templates',
);
// Option 1: return an HTML string (recommended)
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);
echo $html;
// Option 2: include directly (displays the result immediately)
include Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);Variable Passing Methods
The template engine supports three variable passing methods, which you can choose from according to your security needs:
Method 1: Fully open mode (default, backward compatible)
// Use global variables (simplest, backward compatible)
$GLOBALS['user'] = $user;
$GLOBALS['data'] = $data;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);Characteristics:
- ✅ Zero learning curve, simple to use
- ⚠️ Templates can access all global variables (including system variables)
- ⚠️ Suited to development environments or scenarios where the template source is trusted
Method 2: Whitelist mode (recommended for production)
// Configure a whitelist so only the specified variables can be accessed by the template
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data', 'items'];
// Usage stays the same
$GLOBALS['user'] = $user;
$GLOBALS['data'] = $data;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);Characteristics:
- ✅ Balances security and ease of use
- ✅ Only the specified variables can be accessed by the template
- ✅ Recommended for production
Method 3: Explicit passing mode (most secure)
Passing arguments between templates (v1.12.0): the template directive supports with= argument passing and only isolation—
<!--{template child.htm with=["k"=>$v]}-->(inherited context + with overrides),<!--{template child.htm with=[...] only}-->(pass only with, no inheritance),<!--{template child.htm only}-->(empty-context isolated inclusion). See "template argument passing" in syntax.md.
Method 3.1: On-demand plugins (v1.12.0)
The six feature plugins are not part of the builtin auto-load chain; include them explicitly on demand:
require_once 'plugins/pagination.php'; // pagination page_links
require_once 'plugins/asset.php'; // asset versioning asset
require_once 'plugins/text.php'; // slug/excerpt/mask
require_once 'plugins/number.php'; // filesize/money/percent
require_once 'plugins/nav.php'; // nav_active/query_merge
require_once 'plugins/seo.php'; // seo_meta/seo_og/seo_jsonld// Pass variables explicitly for full control over variable access
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
'user' => $user,
'data' => $data,
'items' => $items
]);Characteristics:
- ✅ Most secure, with full control over variable access
- ✅ Does not rely on global variables
- ✅ Suited to scenarios with high security requirements
Configuration Reference
The variable extraction mode is configured through $GLOBALS['siteConf']['template_vars_mode']:
'open'(default): fully open mode, extracts all global variables'whitelist': whitelist mode, extracts only the specified variables'explicit': explicit mode, uses only explicitly passed variables
Note:
- If variables are passed explicitly through the API (the
$varsparameter ofoutString()), the configuration is ignored and the explicit variables are used directly - The
siteConfvariable is always included (the template engine needs it)
Usage Scenarios
Scenario 1: Procedural usage (file top level)
<?php
// index.php - file top level
require_once 'Template.php';
$tplDir = '/path/to/templates/';
$cacheDir = '/path/to/cache/';
// Option 1: use global variables (backward compatible)
$GLOBALS['user'] = $user;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);
// Option 2: pass explicitly (recommended, safer)
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, ['user' => $user]);Scenario 2: Usage inside a function
<?php
// functions.php
function renderUserProfile($userId) {
$tplDir = '/path/to/templates/';
$cacheDir = '/path/to/cache/';
// Fetch data (local variables)
$user = getUserById($userId);
$posts = getUserPosts($userId);
$stats = getUserStats($userId);
// Recommended: pass explicitly (avoids polluting global variables)
return Zandy_Template::outString('user_profile.htm', $tplDir, $cacheDir, false, [
'user' => $user,
'posts' => $posts,
'stats' => $stats
]);
}Scenario 3: Usage inside a class method
<?php
// Controller.php
class UserController {
private $tplDir = '/path/to/templates/';
private $cacheDir = '/path/to/cache/';
public function showProfile($userId) {
// Fetch data (local variables)
$user = $this->getUserById($userId);
$posts = $this->getUserPosts($userId);
// Recommended: pass explicitly
return Zandy_Template::outString('user_profile.htm', $this->tplDir, $this->cacheDir, false, [
'user' => $user,
'posts' => $posts
]);
}
public function renderProfile($userId) {
// Use includeTemplate() (suited to direct output)
$user = $this->getUserById($userId);
$posts = $this->getUserPosts($userId);
Zandy_Template::includeTemplate('user_profile.htm', $this->tplDir, $this->cacheDir, false, [
'user' => $user,
'posts' => $posts
]);
}
}Scenario 4: Using outCache() + include
<?php
// Procedural usage
$GLOBALS['user'] = $user;
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract(Zandy_Template::getTemplateVars()); // uses the configured mode
include $cacheFile;
// Usage inside a function (recommended)
function renderPage() {
$user = getUser();
// Option 1: use includeTemplate() (most recommended)
Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir, false, [
'user' => $user
]);
// Option 2: use the getTemplateVars() helper
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract(Zandy_Template::getTemplateVars(['user' => $user]));
include $cacheFile;
}Scenario 5: Using template test (Tests) syntax
<!-- user_list.htm -->
<!--{if $users is array and is not empty}-->
<ul>
<!--{loop $users as $user}-->
<li>
<!--{if $user is not null}-->
<strong>{$user['name']}</strong>
<!--{if $user['email'] is not empty}-->
<span>{$user['email']}</span>
<!--{/if}-->
<!--{else}-->
<em>User does not exist</em>
<!--{/if}-->
</li>
<!--{/loop}-->
</ul>
<!--{elseif $users is null}-->
<p>Failed to load data</p>
<!--{else}-->
<p>No users yet</p>
<!--{/if}-->Explanation:
- Use
is arrayto check whether a variable is an array - Use
is not emptyto check whether a variable is not empty - Use the chained syntax
andor&&to join multiple tests - Improves code readability and reduces errors
Scenario 6: Using macro definitions (Macros)
<!-- Define a macro: format a date -->
<!--{macro name="formatDate" date="" format="Y-m-d"}-->
<span class="date">{echo date($format, strtotime($date))}</span>
<!--{/macro}-->
<!-- Define a macro: show a user information card -->
<!--{macro name="userCard" user="" showEmail="true"}-->
<div class="user-card">
<h3>{$user['name']}</h3>
<!--{if $showEmail == "true"}-->
<p>{$user['email']}</p>
<!--{/if}-->
</div>
<!--{/macro}-->
<!-- Call a macro: using string arguments -->
<p>Publish date: <!--{call name="formatDate" date="2026-01-15" format="Y-m-d H:i:s"}--></p>
<!-- Call a macro: using variable arguments -->
<p>Publish date: <!--{call name="formatDate" date="$postDate" format="Y-m-d"}--></p>
<!-- Call a macro: multiple arguments -->
<!--{call name="userCard" user="$currentUser" showEmail="false"}-->
<!-- Use a macro inside a loop -->
<!--{loop $users as $user}-->
<!--{call name="userCard" user="$user" showEmail="true"}-->
<!--{/loop}-->The plugin must be loaded before use:
require_once 'plugins/macros.php';Explanation:
- Macro definitions let you define reusable code blocks, similar to functions
- Argument passing is supported; arguments may be string literals or variables
- Default argument values are supported and can be overridden at call time
- Macros are processed at compile time, with zero runtime overhead
- Suited to repeated UI components (such as user cards, date formatting and so on)
Best Practices
1. Variable Passing
Recommended:
- Inside functions/class methods: pass variables explicitly to avoid polluting global variables
- Procedural usage:
$GLOBALSor explicit passing may be used - Production environment: use whitelist mode or explicit passing mode
Not recommended:
- Using
$GLOBALSinside functions (pollutes global variables) - Using fully open mode in production (security risk)
1.1 Plugin Loading Notes
- Filters (
|escape,|upper,|truncateand so on) are provided byplugins/filters.php: with a Composer installation they are loaded automatically viaautoload.files; a manual installation requires you torequire_oncethem yourself, otherwise{$var|escape}reports an "unregistered filter" error at compile time - Composer full-load note:
autoload.filesloads all built-in plugins (including template inheritance, fragment cache, debug-info and so on). In templates that do not use inheritance,<!--{block}-->tags are processed by the inheritance plugin according to standard semantics; if you need strictly on-demand loading, switch to a manual installation and include only the plugins you need
1.2 Debugging and PHP Capability Syntax
- The
<!--{debug-info}-->family of directives is gated at runtime bytpl_debug: no output when disabled (production safe) {echo ...},<!--{php}-->and{CONSTANT}are PHP capability syntax: the template source must be trusted{CONSTANT}referencing an undefined constant degrades safely to empty output (PHP 8 compatible)$,\nand${...}in static text are output verbatim, without PHP interpolation
2. outCache Scenarios
Recommended:
- Use the
includeTemplate()method (most recommended) - Use the
getTemplateVars()helper
Not recommended:
- Using
extract($GLOBALS)directly (security risk)
3. Template Test (Tests) Syntax
Recommended:
- Use test syntax such as
is empty,is nullandis arrayto improve code readability - Use the chained syntax
and/&&oror/||to join multiple tests - When checking arrays, use
is array and is not emptyto ensure the array exists and is not empty
Example:
<!-- ✅ Recommended: use template test syntax -->
<!--{if $items is array and is not empty}-->
<!-- process the array -->
<!--{/if}-->
<!-- ❌ Not recommended: mixed style (unsupported) -->
<!--{if $items is array && !empty($items)}-->
<!-- this style causes a syntax error -->
<!--{/if}-->Not recommended:
- Calling PHP functions directly inside
istest syntax (such as&& !empty($var)) - Use the chained syntax
and is not emptyinstead
4. Macro Definitions (Macros)
Recommended:
- Use macro definitions to encapsulate repeated UI components (such as user cards, date formatting and so on)
- Set reasonable default values for macro arguments to improve ease of use
- Use macros inside loops to reduce duplicated code
Example:
<!-- ✅ Recommended: define a reusable macro -->
<!--{macro name="userCard" user="" showEmail="true"}-->
<div class="user-card">
<h3>{$user['name']}</h3>
<!--{if $showEmail == "true"}-->
<p>{$user['email']}</p>
<!--{/if}-->
</div>
<!--{/macro}-->
<!-- Use the macro inside a loop -->
<!--{loop $users as $user}-->
<!--{call name="userCard" user="$user"}-->
<!--{/loop}-->Not recommended:
- Hard-coding values inside macro definitions (arguments should be used)
- Defining overly complex macros (they should be split into several simple macros)
4. Security Configuration
Development environment:
// The fully open mode (default) may be used for convenient debugging
// No extra configuration neededProduction environment:
// Whitelist mode is recommended
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data', 'items'];High security requirements:
// Use explicit passing mode
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
'user' => $user,
'data' => $data
]);4. HTML Escaping and XSS Protection
Escaping strategy:
- Default behavior: no escaping (keeps backward compatibility)
- Escaping method 1: enable
$GLOBALS['siteConf']['auto_escape'] = trueglobally—{$var}output is escaped automatically (only affects the{$...}output syntax;{...}in CSS/JS is unaffected) - Escaping method 2: add the
|escapemodifier manually when escaping is needed (⚠️ filters are provided byplugins/filters.php, which must be loaded before use, otherwise{$var|escape}fails to compile)
Usage scenarios:
User input (must be escaped):
<!-- ✅ Correct: escape user input to prevent XSS attacks --> Username: {$username|escape} Comment: {$comment|escape} Search keyword: {$keyword|escape}System content (may be left unescaped):
<!-- ✅ Acceptable: system-generated content --> Title: {$title} Description: {$description}Filter chains:
<!-- Multiple filters can be combined --> {$username|upper|escape} <!-- uppercase first, then escape --> {$description|truncate:50|escape} <!-- truncate first, then escape -->
Security tips:
- ⚠️ User input must be escaped to prevent XSS attacks
- ✅ System content may be left unescaped, but the content must be safe
- 📖 For more security advice please refer to the Security Guide
5. Untrusted Template Source
If the template source is untrusted, you must:
- Use explicit passing mode
- Disable PHP code blocks (where possible)
- Strictly validate template paths
- All user input must be escaped (using
|escape)
More Information
- API Reference - Complete API documentation
- Syntax Reference - Complete template syntax
- Security Guide - Secure usage guide
- Performance Optimization Guide - Performance optimization tips and best practices
- Plugin Development Guide - Detailed plugin development instructions
- Example Code - Usage examples