← Documentation

Template Syntax Reference

This document is the complete syntax reference for the Zandy_Template template engine.

Contents

Delimiter Rules

Logic Control Statements

Use <!--{ }--> (wrapped in an HTML comment, so browser previews keep the page structure intact)

Applies to:

Example:

<!--{if $condition}-->
<!--{loop $items as $item}-->
<!--{template header.htm}-->

Variable Output

Use { } (concise, does not break the structure)

Applies to:

Example:

{$user['name']}
{echo date('Y-m-d')}
{time}

Delimiter Configuration (Fully Combinable)

The 4 delimiter constants can be pre-defined before requiring the engine (defaults above apply when not defined):

<?php
// Must be defined BEFORE requiring Template.php (the engine guards with defined()
// and never overwrites externally pre-defined values)
define('ZANDY_TEMPLATE_DELIMITER_LOGIC_LEFT', '[%');
define('ZANDY_TEMPLATE_DELIMITER_LOGIC_RIGHT', '%]');
define('ZANDY_TEMPLATE_DELIMITER_VAR_LEFT', '{$');
define('ZANDY_TEMPLATE_DELIMITER_VAR_RIGHT', '$}');

require_once 'Template.php';

Combination rules and automatic disambiguation — the LOGIC and VAR left delimiters fall into three relationships; the lexer disambiguates automatically:

Relationship Shape Example Disambiguation
Separate No overlap <!--{ }--> + { } Pure position: earliest candidate wins
Same-position Identical, or one is a prefix of the other { } + { }, [[ ]] + [[ ]] Output form first: {$v} / {time} / {CONST} / {echo ...} / {LANG ...} / pipe recognized → output; otherwise → logic tag ({if $x} is logic, CSS {color:red} is static text)
Containment LOGIC_LEFT ends with VAR_LEFT <!--{ }--> + { }, [[{ }]] + { } LOGIC first: complete pairing AND first word is a known directive name → logic tag; else if an output form is recognized → treated as VAR ([[{$v}]] → [[ static + output + ]] static); otherwise → directive kept verbatim

Compile-time validation (on first use): any delimiter that is an empty string or contains a NUL byte → clear error and halt. Containment/same-position shapes are allowed (fallback disambiguation above).

Examples (common combos; the full syntax surface works identically):

// Default: HTML-comment-wrapped logic + brace output
// <!--{if $x}-->...<!--{/if}--> and {$v}

// Square brackets (same shape for logic and output)
define('ZANDY_TEMPLATE_DELIMITER_LOGIC_LEFT', '[[');
define('ZANDY_TEMPLATE_DELIMITER_LOGIC_RIGHT', ']]');
define('ZANDY_TEMPLATE_DELIMITER_VAR_LEFT', '[[');
define('ZANDY_TEMPLATE_DELIMITER_VAR_RIGHT', ']]');
// [[if $x]]...[[/if]] and [[$v]]

// Mainstream brace style (same shape for logic and output)
define('ZANDY_TEMPLATE_DELIMITER_LOGIC_LEFT', '{');
define('ZANDY_TEMPLATE_DELIMITER_LOGIC_RIGHT', '}');
define('ZANDY_TEMPLATE_DELIMITER_VAR_LEFT', '{');
define('ZANDY_TEMPLATE_DELIMITER_VAR_RIGHT', '}');
// {if $x}...{/if} and {$v}; CSS {color:red} stays static

// Percent tags + delimited variable output
define('ZANDY_TEMPLATE_DELIMITER_LOGIC_LEFT', '[%');
define('ZANDY_TEMPLATE_DELIMITER_LOGIC_RIGHT', '%]');
define('ZANDY_TEMPLATE_DELIMITER_VAR_LEFT', '{$');
define('ZANDY_TEMPLATE_DELIMITER_VAR_RIGHT', '$}');
// [%if $x%]...[%/if%] and {$$v$}

Template comments, whitespace control modifiers and literal blocks all follow the LOGIC delimiters: [%* note *%], [%if $x-%], [%literal%]...[%/literal%].

Known limitations:

Variable Output

Basic Syntax

{$variable}                    <!-- simple variable -->
{$array['key']}               <!-- array access -->
{$object->property}           <!-- object property -->
{$array['key1']['key2']}      <!-- multi-dimensional array -->
{$object->method()->property} <!-- method chain -->

Example

<!-- output user information -->
<h1>{$user['name']}</h1>
<p>邮箱: {$user['email']}</p>
<p>年龄: {$user['profile']['age']}</p>

HTML Escaping (Preventing XSS Attacks)

Escaping strategies:

Syntax:

<!-- escaping: prevents XSS attacks -->
{$userInput|escape}

<!-- no escaping: system-generated content -->
{$systemContent}

<!-- automatic escaping (when auto_escape=true) -->
{$userInput}  <!-- escaped automatically -->

<!-- disable automatic escaping (when auto_escape=true) -->
{$systemContent|raw}  <!-- not escaped -->

Usage scenarios:

  1. User input (must be escaped):

    <!-- ✅ correct: escape user input -->
    用户名:{$username|escape}
    评论:{$comment|escape}
    搜索关键词:{$keyword|escape}
  2. System content (may stay unescaped):

    <!-- ✅ acceptable: system-generated content -->
    标题:{$title}
    描述:{$description}
  3. Filter chains (multiple filters may be chained):

    <!-- several filters can be combined; they run left to right -->
    {$username|upper|escape}              <!-- uppercase first, then escape -->
    {$description|truncate:50|escape}    <!-- truncate first, then escape -->
    {$text|lower|truncate:15|escape}     <!-- lowercase, then truncate, then escape -->

    Filter chain execution order:

    • filters run from left to right
    • each filter's output becomes the input of the next filter
    • for example, {$var|upper|escape} produces htmlspecialchars(strtoupper($var), ENT_QUOTES, 'UTF-8')

    Quoted parameter support (use it when a parameter contains the | character):

    {$var|truncate:"10|20"|escape}    <!-- double quotes: the parameter is "10|20" -->
    {$var|truncate:'10|20'|escape}    <!-- single quotes: the parameter is '10|20' -->
    {$var|truncate:10|escape}         <!-- no quotes: the parameter is 10 (backward compatible) -->

    Notes:

    • when a filter parameter contains the | character, the parameter must be wrapped in quotes
    • both single and double quotes are supported
    • the quotes are stripped automatically and the value is handed to the filter handler
    • escaped quotes are supported: {$var|filter:"param\"value"|escape}

Automatic escaping configuration:

  1. Enabling automatic escaping:

    $GLOBALS['siteConf']['auto_escape'] = true;
    • once enabled, every {$var} (no filter) is escaped automatically
    • every {$var|filter} (has filters but neither escape nor raw) gets escaping added automatically
    • {$var|raw} disables automatic escaping
  2. Explicitly disabling automatic escaping:

    $GLOBALS['siteConf']['auto_escape'] = false;
    • turns automatic escaping off explicitly; the behavior is the same as not setting it
  3. Not set (default):

    • when auto_escape is not set, automatic escaping is off by default (backward compatible)

Automatic escaping logic:

Syntax auto_escape=true auto_escape=false auto_escape unset
{$var} escaped automatically not escaped not escaped
{$var|escape} escaped escaped escaped
{$var|raw} not escaped not escaped not escaped
{$var|upper} escaped automatically not escaped not escaped
{$var|upper|escape} escaped escaped escaped
{$var|upper|raw} not escaped not escaped not escaped

Escaping implementation:

Security notes:

literal Block

Syntax

<!--{literal}-->
    此处内容逐字呈现:{$var}、<!--{if $x}-->、{$a|filter} 等模板语法
    一律不解析、不插值,适合展示模板语法本身或嵌入 JS 模板字符串。
<!--{/literal}-->

Description

Compile Switches

Switch Config (siteConf / Engine config) Description
Sandbox mode tpl_sandbox => true Disables the php/include/include_once directives and superglobal access ($_GET/$_POST/$_REQUEST/$_SERVER/$_COOKIE/$_FILES/$_ENV/$_SESSION) at compile time; diagnostics include the template line number
Strict variables tpl_strict_variables => true Simple variable output compiles an isset check; undefined variables raise a runtime warning (rendering is not interrupted); off by default (silently outputs empty)
Structural diagnostics Zandy_Template::validate($tpl) Collects every structural error and returns a diagnostics array (no halt); batch pre-check for existing templates before an upgrade
Structured diagnostics Zandy_Template::validateDetailed($tpl) Each diagnostic carries an error code (ZTE101-107) / line / fix suggestion / source snippet — ready for IDE and CI consumption
Runtime error mapping tpl_error_map => true PHP 7+: wraps runtime exceptions from outString into Zandy_Template_RuntimeException carrying the template name and template line (source-map lookup; off by default)
Compile lock timeout tpl_lock_timeout => 30 Total lock-wait timeout in seconds (default 30); degrades to unlocked compile with an error_log notice
Include depth limit tpl_include_max_depth => 32 template nesting depth limit (default 32); over-limit halts with an explicit message, cycles are detected
eval fallback tpl_eval_fallback (set false to disable) On by default: when both exec and opcache are missing, eval provides the syntax fallback (it executes the compiled artifact once in full, equivalent to include side effects — templates with write operations fire twice per compile cycle); when disabled, environments missing both degrade to "cannot validate" plus an error_log warning

Instantiation API (v1.9+, static entry points @deprecated since v1.10)

$engine = new Zandy_Template_Engine(array(
    'tplDir' => './templates/',
    'cacheDir' => './cache/',
    'auto_escape' => true,
    'tpl_sandbox' => true,
));
echo $engine->outString('hello.htm', array('name' => 'W'));  // render (vars passed explicitly)
$code = $engine->parse('{$x}');                              // compile
$diags = $engine->validate($tpl);                            // structural diagnostics

autoescape Context Escaping Block

<script>var s = <!--{autoescape js}-->{$userInput}<!--{/autoescape}-->;</script>
<a href="?q=<!--{autoescape url}-->{$q}<!--{/autoescape}-->">

trans i18n Pluralization Block

<!--{trans key="apples" count="$n" zero="无苹果" one="1 apple" other="%d apples"}-->

Loops

📖 Detailed documentation: see the Loop Directive full feature documentation for the complete feature description, 25 usage examples and edge-case test cases.

Basic Loop Syntax

Zandy_Template supports several loop formats, matched in the following order (from most specific to most abstract):

Supported formats (6 in total):

  1. <!--{loop $arr AS $key => $value}--> - with AS and =>
  2. <!--{loop $arr AS $key $value}--> - with AS plus key and value
  3. <!--{loop $arr AS $value}--> - with AS and value
  4. <!--{loop $arr $key => $value}--> - with =>
  5. <!--{loop $arr $key $value}--> - with key and value
  6. <!--{loop $arr $value}--> - value only

Note: every format provides the $_zte_loop object automatically; no parameters need to be specified manually.

Basic Examples

<!-- loop iteration -->
<!--{loop $items as $item}-->
    <li>{$item}</li>
<!--{/loop}-->

<!-- loop iteration (with key/value) -->
<!--{loop $items $k $v}-->
    <p>{$k}: {$v}</p>
<!--{/loop}-->

<!-- loop iteration (AS syntax) -->
<!--{loop $items AS $key => $value}-->
    <p>{$key}: {$value}</p>
<!--{/loop}-->

<!-- loop-else (empty array handling) -->
<!--{loop array() as $v}-->
    <li>{$v}</li>
<!--{loop-else}-->
    <p>没有数据</p>
<!--{/loop}-->

<!-- for loop -->
<!--{for $i = 0; $i < 100; $i++}-->
    <span>{$i}</span>
<!--{/for}-->

<!-- nested loop -->
<!--{loop $categories as $category}-->
    <h3>{$category['name']}</h3>
    <ul>
        <!--{loop $category['items'] as $item}-->
            <li>{$item['name']} - {$item['price']}</li>
        <!--{/loop}-->
    </ul>
<!--{/loop}-->

<!-- foreach loop -->
<!--{foreach $items as $item}-->
    <li>{$item}</li>
<!--{/foreach}-->

Loop Index Information (the $_zte_loop Object)

Every loop iteration provides a $_zte_loop object automatically, carrying the loop index information.

Basic usage:

<!--{loop $items AS $item}-->
    <!-- the $_zte_loop object is provided automatically -->
    索引: {$_zte_loop->index}        <!-- starts at 0 -->
    迭代: {$_zte_loop->iteration}   <!-- starts at 1 -->
    第一个: {$_zte_loop->first}      <!-- true/false -->
    最后一个: {$_zte_loop->last}    <!-- true/false -->
    总数: {$_zte_loop->length}       <!-- array length -->
    偶数: {$_zte_loop->even}         <!-- true/false -->
    奇数: {$_zte_loop->odd}          <!-- true/false -->
    剩余: {$_zte_loop->remaining}    <!-- iterations remaining -->
    
    <div class="item-{$_zte_loop->index}">
        {$item}
        <!--{if $_zte_loop->first}-->(第一个)<!--{/if}-->
        <!--{if $_zte_loop->last}-->(最后一个)<!--{/if}-->
    </div>
<!--{/loop}-->

Loop information properties:

Nested loop example:

<!--{loop $users AS $user}-->
    <div class="user-{$_zte_loop->index}">
        <h3>{$user['name']}</h3>
        
        <!--{loop $user['posts'] AS $post}-->
            <div class="post-{$_zte_loop->index}">
                用户索引: {$_zte_loop->parent->index}  <!-- access the outer loop -->
                文章索引: {$_zte_loop->index}          <!-- access the inner loop -->
                {$post['title']}
            </div>
        <!--{/loop}-->
    </div>
<!--{/loop}-->

Backward compatibility:

The name parameter is deprecated but still supported (backward compatible). Using the $_zte_loop object is recommended:

<!--{loop $items AS $item}-->
    <!-- iterate the data only, without generating loop information variables -->
    <div>{$item}</div>
<!--{/loop}-->

Conditionals

if/elseif/else

<!--{if $condition}-->
    <p>条件为真</p>
<!--{elseif $other > 100}-->
    <p>其他条件</p>
<!--{else}-->
    <p>默认</p>
<!--{/if}-->

Supported Expressions

Conditionals accept full PHP expressions:

<!--{if $user['age'] >= 18 && $user['status'] == 'active'}-->
    <p>成年活跃用户</p>
<!--{/if}-->

Template Tests Syntax

A convenient variable test syntax is provided for more readable code:

Basic Syntax

<!--{if $var is empty}-->        <!-- check whether the variable is empty -->
<!--{if $var is not empty}-->   <!-- check whether the variable is not empty -->
<!--{if $var is null}-->        <!-- check whether the variable is null -->
<!--{if $var is not null}-->    <!-- check whether the variable is not null -->
<!--{if $var is array}-->       <!-- check whether the variable is an array -->
<!--{if $var is not array}-->   <!-- check whether the variable is not an array -->
<!--{if $var is object}-->      <!-- check whether the variable is an object -->
<!--{if $var is not object}-->  <!-- check whether the variable is not an object -->

Supported Test Types

Syntax PHP translation Description
$var is empty empty($var) check whether the variable is empty
$var is not empty !empty($var) check whether the variable is not empty
$var is null $var === null check whether the variable is null
$var is not null $var !== null check whether the variable is not null
$var is array is_array($var) check whether the variable is an array
$var is not array !is_array($var) check whether the variable is not an array
$var is object is_object($var) check whether the variable is an object
$var is not object !is_object($var) check whether the variable is not an object
$var is int is_int($var) check whether the variable is an integer
$var is not int !is_int($var) check whether the variable is not an integer
$var is string is_string($var) check whether the variable is a string
$var is not string !is_string($var) check whether the variable is not a string
$var is bool is_bool($var) check whether the variable is a boolean
$var is not bool !is_bool($var) check whether the variable is not a boolean
$var is float is_float($var) check whether the variable is a float
$var is not float !is_float($var) check whether the variable is not a float
$var is numeric is_numeric($var) check whether the variable is numeric (numeric strings included)
$var is not numeric !is_numeric($var) check whether the variable is not numeric
$var is callable is_callable($var) Checks whether the variable is callable (function name / closure / callable array)
$var is not callable !is_callable($var) Checks whether the variable is not callable
$var is scalar is_scalar($var) Checks whether the variable is scalar (int/float/string/bool)
$var is not scalar !is_scalar($var) Checks whether the variable is not scalar

is tests are compile-time syntactic sugar — the equivalent native PHP form (right column) always works in expressions and either may be used; chaining ($a is int and $b is string) and subject-omitted combinations ($a is int and is not string) work for both new and old types.

Chaining Syntax

Multiple tests can be joined with and/&& or or/||:

<!-- using the and operator -->
<!--{if $var is array and is not empty}-->
    <p>数组且不为空</p>
<!--{/if}-->

<!-- using the && operator (same as and) -->
<!--{if $var is array && is not empty}-->
    <p>数组且不为空</p>
<!--{/if}-->

<!-- using the or operator -->
<!--{if $var is null or is empty}-->
    <p>为 null 或为空</p>
<!--{/if}-->

<!-- using the || operator (same as or) -->
<!--{if $var is null || is empty}-->
    <p>为 null 或为空</p>
<!--{/if}-->

Chaining notes:

Usage Examples

<!-- check whether the user exists -->
<!--{if $user is not null}-->
    <h1>欢迎,{$user['name']}!</h1>
<!--{else}-->
    <p>请先登录</p>
<!--{/if}-->

<!-- check whether the array exists and is not empty -->
<!--{if $items is array and is not empty}-->
    <ul>
        <!--{loop $items as $item}-->
            <li>{$item}</li>
        <!--{/loop}-->
    </ul>
<!--{else}-->
    <p>暂无数据</p>
<!--{/if}-->

<!-- check the variable type -->
<!--{if $data is array}-->
    <p>数据是数组</p>
<!--{elseif $data is object}-->
    <p>数据是对象</p>
<!--{else}-->
    <p>数据是其他类型</p>
<!--{/if}-->

Notes

  1. An ordinary PHP expression (including function calls) may follow an is test directly

    <!-- ✅ correct: the is test comes first, any expression may follow verbatim -->
    <!--{if $var is array && !empty($var)}-->
    <!--{if $var is empty or ($other > 1 and $other < 9)}-->
  2. Compile-time translation: is test syntax is translated into a standard PHP expression at compile time, with zero runtime overhead

  3. Mixing with standard PHP expressions: an is test must sit at the start of the statement; after it, any ordinary expression may follow, joined with and/or/&&/|| (parenthesized groups included)

  4. Parentheses are not supported around is-tests (($a is empty), !($a is empty)) — the converter only recognizes bare forms at the start of the statement; use the native PHP equivalent (empty($a) / !empty($a)) when parentheses are needed.

  5. is-tests only accept simple variables and array subscripts ($a, $a['k']) — for property access ($obj->prop is empty) use the native form (empty($obj->prop)).

    <!-- ✅ correct: is test first + any operator -->
    <!--{if $var is empty or $other > 1}-->
    <!--{if $var is array && count($var) > 0}-->
    <!--{if $var is not empty or ($status == 1 and $level < 9)}-->
    
    <!-- ❌ wrong: the is test is not at the start of the statement (an ordinary condition comes first) — unsupported;
         the whole statement is kept verbatim and the compile-time syntax check reports it explicitly -->
    <!--{if $other > 1 and $var is empty}-->
    <!-- ✅ correct: rewrite it so the is test comes first -->
    <!--{if $var is empty and $other > 1}-->

Switch Statement

Basic Syntax

<!--{switch $value}-->
    <!--{case 1}-->
        <p>值为 1</p>
    <!--{break-case 2}-->
        <p>值为 2</p>
    <!--{break-default}-->
        <p>默认值</p>
    <!--{default}-->
        <p>其他默认值</p>
<!--{/switch}-->

Features

Example

<!--{switch $status}-->
    <!--{case 'active'}-->
        <span class="active">活跃</span>
    <!--{break-case 'pending'}-->
        <span class="pending">待审核</span>
    <!--{break-default}-->
        <span class="inactive">未激活</span>
    <!--{default}-->
        <span>未知状态</span>
<!--{/switch}-->

Template Inheritance

Template inheritance lets a child template inherit from a parent template and override or extend the parent's content blocks, cutting duplication and making templates easier to maintain.

A plugin must be loaded before use:

require_once 'plugins/template-inheritance.php';

extends Directive

Declares the inheritance relationship; it must be on the first line of the template (whitespace and comments are ignored):

<!--{extends base.htm}-->

Notes:

block Directive

Defines an overridable content block:

<!--{block name="content"}-->
    默认内容
<!--{/block}-->

Notes:

parent Call

Calls the parent template's block content from inside a child template's block:

<!--{block name="content"}-->
    <p>子模板内容</p>
    <!--{parent}-->  <!-- call the parent template's block content -->
<!--{/block}-->

append and prepend Modes

append mode: append after the parent content:

<!--{block name="header" append}-->
    <nav>导航菜单</nav>
<!--{/block}-->

prepend mode: prepend before the parent content:

<!--{block name="header" prepend}-->
    <nav>导航菜单</nav>
<!--{/block}-->

Complete Example

Parent template base.htm:

<!DOCTYPE html>
<html>
<head>
    <title><!--{block name="title"}-->默认标题<!--{/block}--></title>
</head>
<body>
    <header><!--{block name="header"}-->默认头部<!--{/block}--></header>
    <main><!--{block name="content"}-->默认内容<!--{/block}--></main>
    <footer><!--{block name="footer"}-->默认底部<!--{/block}--></footer>
</body>
</html>

Child template page.htm:

<!--{extends base.htm}-->

<!--{block name="title"}-->页面标题<!--{/block}-->

<!--{block name="content"}-->
    <p>页面内容</p>
    <!--{parent}-->  <!-- call the parent template's block content -->
<!--{/block}-->

Multi-Level Inheritance

Multi-level inheritance is supported (A extends B, B extends C):

<!-- layout.htm -->
<!DOCTYPE html>
<html>
<head><!--{block name="head"}--><!--{/block}--></head>
<body><!--{block name="body"}--><!--{/block}--></body>
</html>

<!-- base.htm -->
<!--{extends layout.htm}-->
<!--{block name="head"}-->
    <title><!--{block name="title"}-->默认标题<!--{/block}--></title>
<!--{/block}-->

<!-- page.htm -->
<!--{extends base.htm}-->
<!--{block name="title"}-->页面标题<!--{/block}-->

Notes

  1. extends position: the extends directive must be on the first line of the template (whitespace and comments are ignored)
  2. block names: block names must be unique within a template
  3. parent call: only valid inside a block, never outside one
  4. performance: multi-level inheritance increases parse time; no more than 3 levels is recommended
  5. cyclic inheritance detection: cycles are detected and blocked automatically

More information:

Template Fragment Cache

Basic Syntax

<!--{cache key="缓存键" time="缓存时间(秒)"}-->
    要缓存的内容
<!--{/cache}-->

Full Syntax (all attributes supported)

<!--{cache key="缓存键" time="缓存时间(秒)" if="条件表达式" tags="标签1,标签2" depends="依赖版本"}-->
    要缓存的内容
<!--{/cache}-->

Parameter notes:

Usage Examples

Basic usage:

<!--{cache key="user_list" time="3600"}-->
    <div>用户列表内容</div>
<!--{/cache}-->

Dynamic cache key and lifetime:

<!--{cache key="$dynamicKey" time="$cacheTime"}-->
    <div>动态缓存键和时间</div>
<!--{/cache}-->

Conditional caching:

<!--{cache key="user_profile" time="7200" if="$isLoggedIn"}-->
    <div>只有登录用户才缓存</div>
<!--{/cache}-->

Cache tags (bulk clearing):

<!--{cache key="product_list" time="3600" tags="product,catalog"}-->
    <div>产品列表(可批量清除)</div>
<!--{/cache}-->

Cache dependency (automatic invalidation):

<!--{cache key="user_data" time="3600" depends="$userVersion"}-->
    <div>用户数据(依赖版本号,版本变化时自动失效)</div>
<!--{/cache}-->

Nested caching:

<!--{cache key="outer" time="3600"}-->
    <div>外层缓存
        <!--{cache key="inner" time="1800"}-->
            <div>内层缓存</div>
        <!--{/cache}-->
    </div>
<!--{/cache}-->

Advanced Configuration

Enable cache compression (optional, off by default):

// define it in PHP code
define('ZTE_FRAGMENT_CACHE_COMPRESS', true);
define('ZTE_FRAGMENT_CACHE_COMPRESS_THRESHOLD', 10240); // only compress content larger than 10KB

Enable helper-function mode (optional, off by default):

// define it in PHP code
define('ZTE_FRAGMENT_CACHE_USE_HELPER', true);

Enable debug mode (optional, off by default):

// define it in PHP code
define('ZTE_FRAGMENT_CACHE_DEBUG', true);

Cache Management API

Clear the cache by tag:

require_once 'plugins/fragment-cache.php';
zte_clear_cache_by_tag('product'); // clear every cache entry tagged 'product'

Clear all fragment caches:

zte_clear_all_fragment_cache();

Get cache statistics (debug mode required):

$stats = zte_get_fragment_cache_stats();
// returns: ['hit' => 10, 'miss' => 5, 'skip' => 2, 'keys' => [...], 'hit_rate' => 58.82]

Reset the statistics:

zte_reset_fragment_cache_stats();

Notes

  1. cache directory: cache files are stored in "/fragments/" — the base directory is the explicitly passed $cacheDir argument, falling back to siteConf's tplCacheBaseDir when empty (the cacheDir convenience key on an Engine instance maps to the same key)
  2. cache key uniqueness: make sure different templates use different cache keys to avoid collisions
  3. dependency changes: when the depends attribute value changes, the cache is invalidated automatically
  4. conditional caching: when the if condition is false, the content still runs but is not cached
  5. nested caching: multiple levels are supported; inner caches are independent of outer ones
  6. performance: cache key computation is already optimized — the fixed part is computed at compile time

More information:

Template Inclusion

Basic Syntax

<!--{template header.htm}-->
<!--{template ../common/footer.htm}-->

Path Rules

Note: child template paths are resolved relative to the parent template.

For example, with this directory layout:

common/
  ├── header.htm
  └── footer.htm
index/
  ├── index.htm
  └── menu.htm

Inside index/index.htm:

<!--{template ../common/header.htm}-->
<!--{template menu.htm}-->
<!--{template ../common/footer.htm}-->

File Inclusion

include/include_once

<!--{include helper.php}-->
<!--{include_once helper.php}-->

Note: the included file must be a PHP file and is executed directly.

Expressions and PHP Code

echo Expression

{echo date('Y-m-d H:i:s')}
{echo $a ? 'a' : 'b'}
{echo xxx($aaa, $bbb)}

PHP Code Block

<!--{php}-->
    if ($a) { 
        echo 'a'; 
    }
<!--{/php}-->

set Variable

<!--{set $var = 'value'}-->
<!--{set $count = count($items)}-->

Time Functions

time

Outputs the current timestamp:

{time}

now

Outputs the current date and time (format: Y-m-d H:i:s):

{now}

date

Outputs a formatted date:

{date "Y-m-d"}
{date 'Y-m-d H:i:s'}  <!-- single quotes supported -->

PHP Constants

Outputs PHP constants (all caps with underscores):

{PHP_VERSION}       <!-- outputs the PHP version -->
{CONSTANT_NAME}     <!-- outputs any PHP constant -->

Language Packs

Standard Form

{$_LANG['title']}

Shorthand Form

{LANG title}

Notes:

Template Comments

Template comments are removed at compile time and never appear in the final output:

<!--{*这是注释内容*}-->

Plugin System

Zandy_Template has a plugin system that lets users extend template functionality.

Built-in Plugins

Load the built-in plugins through plugins/builtin.php:

require_once 'plugins/builtin.php';

The built-in plugins include:

Block-plugin nesting and capability boundary (v1.15.0)

Since v1.15.0, block plugin directives support same-name nesting (e.g. custom-loop inside custom-loop): balanced pair extraction captures the full nested block and replaces layer by layer from the inside out — nested loop structure and inner data-source independence are correct (the legacy greedy truncation + orphan close-tag leak is fixed).

Capability forms (contract v2, v1.15.0):

Custom Plugins

Custom directive and function plugins can be registered; see the Plugin development guide and the API reference.

More Information

Loop else Semantics

template Parameters (with=)

<!--{template child.htm}-->                            <!-- classic include: the child template inherits every variable in the current scope -->
<!--{template child.htm with=["k"=>"v"]}-->            <!-- with parameters: an array expression whose key/value pairs are injected into the child -->
<!--{template child.htm with=$data}-->                 <!-- expression: an array returned by a variable/function works too -->

Macro Definitions

Define reusable, parameterized template fragments (requires the plugins/macros.php plugin):

<!--{macro name="formatDate" date="" format="Y-m-d"}-->
    {echo date($format, strtotime($date))}
<!--{/macro}-->

<p>Published: <!--{call name="formatDate" date="$postDate" format="Y-m-d H:i:s"}--></p>

On-Demand Plugins (not in the builtin auto-load chain)

The plugins below must be pulled in explicitly with require_once 'plugins/<name>.php' (new in v1.12.0):

Plugin Usage Description
pagination {$p|page_links:$tp,?page=%d} Pagination link HTML (window/ellipsis/prev-next; the third parameter is the window radius)
asset {"css/app.css"|asset} Asset version query ?v=<mtime> (the second parameter is the docroot, DOCUMENT_ROOT by default; external URLs, URLs that already carry a query, and missing files are returned as-is)
text {$t|slug} / {$t|excerpt:100} / {$t|mask:3,4} URL-friendly slug (Unicode letters preserved) / excerpt truncation with an ellipsis / masking (keep the first 3 and last 4)
number {$n|filesize} / {$n|money:"¥"} / {$n|percent:1} human-readable byte sizes / currency / percentage (input as a decimal)
nav {"/about"|nav_active} / {"a=1"|query_merge:["p"=>2]} output when the current path matches (prefix match, so /about does not wrongly hit /abouts) / query merging
seo <!--{seo_meta title=".." description=".."}--> and friends meta/og tag groups (attribute values starting with $ are expressions), <!--{seo_jsonld $data}--> JSON-LD

Filter parameter wrapping convention: values starting with $ are passed through as expressions, everything else is treated as a string literal; multiple parameters are separated by , (the engine strips the quotes wrapping the whole parameter list, so string parameters can be written bare).

Whitespace Control Modifiers

A   <!--{-if $a}-->X<!--{/if}-->        <!-- left trim: remove the whitespace before the tag → AX -->
<!--{if $a-}-->   X<!--{/if}-->        <!-- right trim: remove the whitespace after the tag → X -->
<!--{-if $a-}-->                       <!-- trim on both sides -->
<!--{-/if-}-->                          <!-- closing tags support it as well -->

Syntax Cheat Sheet (Executable Specification)

This table is a machine-readable syntax specification (docs as tests, #31): test/DocAsTest.php compiles and renders every entry and asserts byte-for-byte equality with the "expected output". Changing engine behavior requires changing the table, and changing the table requires changing the behavior — otherwise the test goes red. Entries are self-contained (vars/siteConf travel with the entry).

[
  {"name": "变量输出·简单", "tpl": "Hello {$name}", "vars": {"name": "Zandy"}, "expect": "Hello Zandy"},
  {"name": "变量输出·数组访问", "tpl": "{$user['name']}", "vars": {"user": {"name": "Zandy"}}, "expect": "Zandy"},
  {"name": "变量输出·多维数组", "tpl": "{$a['b']['c']}", "vars": {"a": {"b": {"c": "deep"}}}, "expect": "deep"},
  {"name": "变量表达式(算术)", "tpl": "N={$a+1}", "vars": {"a": 41}, "expect": "N=42"},
  {"name": "条件 if/elseif/else", "tpl": "<!--{if $n > 10}-->大<!--{elseif $n > 5}-->中<!--{else}-->小<!--{/if}-->", "vars": {"n": 7}, "expect": "中"},
  {"name": "loop 格式1(键值)", "tpl": "<!--{loop $rows AS $k => $v}-->[{$k}={$v}]<!--{/loop}-->", "vars": {"rows": {"a": "1", "b": "2"}}, "expect": "[a=1][b=2]"},
  {"name": "loop 格式6(仅值)", "tpl": "<!--{loop $rows $r}-->{$r};<!--{/loop}-->", "vars": {"rows": ["x", "y"]}, "expect": "x;y;"},
  {"name": "循环索引 $_zte_loop", "tpl": "<!--{loop $rows AS $r}-->{$_zte_loop->index}:{$r} <!--{/loop}-->", "vars": {"rows": ["a", "b"]}, "expect": "0:a 1:b "},
  {"name": "loop-else 空态分支", "tpl": "<!--{loop $rows AS $r}-->{$r}<!--{loop-else}-->空<!--{/loop}-->", "vars": {"rows": []}, "expect": "空"},
  {"name": "foreach + else", "tpl": "<!--{foreach $rows as $r}-->{$r}<!--{foreach-else}-->空<!--{/foreach}-->", "vars": {"rows": ["p"]}, "expect": "p"},
  {"name": "for 循环", "tpl": "<!--{for $i = 0; $i < 3; $i++}-->{$i}<!--{/for}-->", "expect": "012"},
  {"name": "嵌套循环", "tpl": "<!--{loop $grid AS $row}--><!--{loop $row AS $c}-->{$c}<!--{/loop}-->;<!--{/loop}-->", "vars": {"grid": [["a", "b"], ["c"]]}, "expect": "ab;c;"},
  {"name": "switch/case/break-case/default", "tpl": "<!--{switch $x}--><!--{case 'a'}-->A<!--{break-case 'b'}-->B<!--{default}-->D<!--{/switch}-->", "vars": {"x": "b"}, "expect": "BD"},
  {"name": "literal 字面块", "tpl": "<!--{literal}-->{$raw} <!--{if $x}-->y<!--{/if}--><!--{/literal}-->", "expect": "{$raw} <!--{if $x}-->y<!--{/if}-->"},
  {"name": "autoescape js 上下文", "tpl": "<!--{autoescape js}-->{$s}<!--{/autoescape}-->", "vars": {"s": "a\"b"}, "expect": "\"a\\u0022b\""},
  {"name": "autoescape url 上下文", "tpl": "<!--{autoescape url}-->{$q}<!--{/autoescape}-->", "vars": {"q": "a b&c"}, "expect": "a%20b%26c"},
  {"name": "autoescape html 上下文", "tpl": "<!--{autoescape html}-->{$h}<!--{/autoescape}-->", "vars": {"h": "<b>"}, "expect": "&lt;b&gt;"},
  {"name": "trans 复数化(other)", "tpl": "<!--{trans key=\"k\" count=\"$n\" zero=\"无\" one=\"1 个\" other=\"%d 个\"}-->", "vars": {"n": 3}, "expect": "3 个"},
  {"name": "trans 复数化(one)", "tpl": "<!--{trans key=\"k\" count=\"$n\" zero=\"无\" one=\"1 个\" other=\"%d 个\"}-->", "vars": {"n": 1}, "expect": "1 个"},
  {"name": "过滤器 upper", "tpl": "{$s|upper}", "vars": {"s": "abc"}, "expect": "ABC"},
  {"name": "过滤器 lower", "tpl": "{$s|lower}", "vars": {"s": "ABC"}, "expect": "abc"},
  {"name": "过滤器 escape", "tpl": "{$s|escape}", "vars": {"s": "<b>"}, "expect": "&lt;b&gt;"},
  {"name": "过滤器链 upper|escape", "tpl": "{$s|upper|escape}", "vars": {"s": "<x>"}, "expect": "&lt;X&gt;"},
  {"name": "auto_escape 开启(默认转义)", "tpl": "{$s}", "vars": {"s": "<b>"}, "siteConf": {"auto_escape": true}, "expect": "&lt;b&gt;"},
  {"name": "auto_escape 开启 + raw 禁用", "tpl": "{$s|raw}", "vars": {"s": "<b>"}, "siteConf": {"auto_escape": true}, "expect": "<b>"},
  {"name": "set 赋值", "tpl": "<!--{set $v = 'S'}-->{$v}", "expect": "S"},
  {"name": "php 块", "tpl": "<!--{php}-->$pv = 7<!--{/php}-->{$pv}", "expect": "7"},
  {"name": "模板注释(剥离)", "tpl": "A<!--{* 注释 <!--{if $x}--> *}-->B", "expect": "AB"},
  {"name": "echo 表达式", "tpl": "{echo strtoupper($s)}", "vars": {"s": "up"}, "expect": "UP"},
  {"name": "is 测试(not empty)", "tpl": "<!--{if $a is not empty}-->有<!--{/if}-->", "vars": {"a": 1}, "expect": "有"},
  {"name": "is 测试(empty)", "tpl": "<!--{if $a is empty}-->空<!--{/if}-->", "expect": "空"},
  {"name": "is 测试(链式)", "tpl": "<!--{if $a is not empty and $b is empty}-->CH<!--{/if}-->", "vars": {"a": 1, "b": 0}, "expect": "CH"},
  {"name": "LANG 语言包", "tpl": "{LANG greet}", "vars": {"_LANG": {"greet": "你好"}}, "expect": "你好"},
  {"name": "PHP 常量输出", "tpl": "{ZTE_DOC_CONST}", "expect": "DOCV"},
  {"name": "过滤器 capitalize", "tpl": "{$s|capitalize}", "vars": {"s": "hELLO"}, "expect": "Hello"},
  {"name": "过滤器 title", "tpl": "{$s|title}", "vars": {"s": "hello world"}, "expect": "Hello World"},
  {"name": "过滤器 trim", "tpl": "[{$s|trim}]", "vars": {"s": "  x  "}, "expect": "[x]"},
  {"name": "过滤器 length 字符串", "tpl": "{$s|length}", "vars": {"s": "你好ab"}, "expect": "4"},
  {"name": "过滤器 length 数组", "tpl": "{$a|length}", "vars": {"a": [1, 2, 3]}, "expect": "3"},
  {"name": "过滤器 number_format", "tpl": "{$n|number_format:2}", "vars": {"n": 1234.567}, "expect": "1,234.57"},
  {"name": "过滤器 json", "tpl": "{$a|json}", "vars": {"a": {"k": "v"}}, "expect": "{\"k\":\"v\"}"},
  {"name": "过滤器 slice 字符串", "tpl": "{$s|slice:1,2}", "vars": {"s": "abcdef"}, "expect": "bc"},
  {"name": "过滤器 first 数组", "tpl": "{$a|first}", "vars": {"a": ["f", "s"]}, "expect": "f"},
  {"name": "过滤器 last 数组", "tpl": "{$a|last}", "vars": {"a": ["f", "s"]}, "expect": "s"},
  {"name": "过滤器 reverse 链 json", "tpl": "{$a|reverse|json}", "vars": {"a": [1, 2, 3]}, "expect": "[3,2,1]"},
  {"name": "过滤器 merge 链 json", "tpl": "{$a|merge:$b|json}", "vars": {"a": {"x": 1}, "b": {"y": 2}}, "expect": "{\"x\":1,\"y\":2}"},
  {"name": "过滤器 round", "tpl": "{$n|round:1}", "vars": {"n": 3.14159}, "expect": "3.1"},
  {"name": "过滤器 abs", "tpl": "{$n|abs}", "vars": {"n": -5}, "expect": "5"},
  {"name": "过滤器 url_encode", "tpl": "{$s|url_encode}", "vars": {"s": "a b"}, "expect": "a%20b"},
  {"name": "trans 命名占位符", "tpl": "<!--{trans key=\"welcome\" name=\"$userName\"}-->", "vars": {"_LANG": {"welcome": "欢迎 {name}!"}, "userName": "Zandy"}, "expect": "欢迎 Zandy!"},
  {"name": "空白控制·左修剪", "tpl": "A   <!--{-if $a}-->X<!--{/if}-->", "vars": {"a": true}, "expect": "AX"},
  {"name": "空白控制·右修剪", "tpl": "<!--{if $a-}-->   X<!--{/if}-->", "vars": {"a": true}, "expect": "X"},
  {"name": "空白控制·闭合标签双侧", "tpl": "A <!--{if $a}-->X<!--{-/if-}--> B", "vars": {"a": true}, "expect": "A XB"},
  {"name": "空白控制·无空白无副作用", "tpl": "A<!--{-if $a-}-->X<!--{/if}-->", "vars": {"a": true}, "expect": "AX"},
  {"name": "空白控制·跨行修剪", "tpl": "A\n\n<!--{-if $a}-->X<!--{/if}-->", "vars": {"a": true}, "expect": "AX"},
  {"name": "template with 基本传参", "tpl": "<!--{template child.htm with=[\"k\"=>\"v\"]}-->", "files": {"child.htm": "K={$k}"}, "expect": "K=v"},
  {"name": "template with 覆盖上下文", "tpl": "<!--{template child.htm with=[\"a\"=>\"new\"]}-->", "vars": {"a": "old"}, "files": {"child.htm": "{$a}"}, "expect": "new"},
  {"name": "template with 继承上下文", "tpl": "<!--{template child.htm with=[\"b\"=>\"B\"]}-->", "vars": {"a": "A"}, "files": {"child.htm": "{$a}-{$b}"}, "expect": "A-B"},
  {"name": "template with 作用域隔离", "tpl": "<!--{template child.htm with=[\"tmp\"=>\"inner\"]}-->[{$tmp}]", "vars": {"tmp": "outer"}, "files": {"child.htm": "{$tmp}"}, "expect": "inner[outer]"},
  {"name": "is int 测试", "tpl": "<!--{if $n is int}-->I<!--{/if}-->", "vars": {"n": 5}, "expect": "I"},
  {"name": "is not int 测试", "tpl": "<!--{if $s is not int}-->NI<!--{/if}-->", "vars": {"s": "x"}, "expect": "NI"},
  {"name": "is string 测试", "tpl": "<!--{if $s is string}-->S<!--{/if}-->", "vars": {"s": "x"}, "expect": "S"},
  {"name": "is not string 测试", "tpl": "<!--{if $n is not string}-->NS<!--{/if}-->", "vars": {"n": 5}, "expect": "NS"},
  {"name": "is bool 测试", "tpl": "<!--{if $b is bool}-->B<!--{/if}-->", "vars": {"b": true}, "expect": "B"},
  {"name": "is not bool 测试", "tpl": "<!--{if $n is not bool}-->NB<!--{/if}-->", "vars": {"n": 1}, "expect": "NB"},
  {"name": "is float 测试", "tpl": "<!--{if $f is float}-->F<!--{/if}-->", "vars": {"f": 1.5}, "expect": "F"},
  {"name": "is not float 测试", "tpl": "<!--{if $n is not float}-->NF<!--{/if}-->", "vars": {"n": 1}, "expect": "NF"},
  {"name": "is numeric 测试", "tpl": "<!--{if $s is numeric}-->NUM<!--{/if}-->", "vars": {"s": "123"}, "expect": "NUM"},
  {"name": "is not numeric 测试", "tpl": "<!--{if $s is not numeric}-->NN<!--{/if}-->", "vars": {"s": "abc"}, "expect": "NN"},
  {"name": "is 链式含新类型", "tpl": "<!--{if $a is int and $b is string}-->OK<!--{/if}-->", "vars": {"a": 1, "b": "x"}, "expect": "OK"},
  {"name": "is 省略主语组合含新类型", "tpl": "<!--{if $a is int and is not string}-->OK<!--{/if}-->", "vars": {"a": 1}, "expect": "OK"},
  {"name": "template with only 隔离", "tpl": "<!--{template child.htm with=[\"a\"=>\"A\"] only}-->", "vars": {"ctx": "C"}, "files": {"child.htm": "{$a}/{$ctx|default:\"无\"}"}, "expect": "A/无"},
  {"name": "template 裸 only 空上下文", "tpl": "<!--{template child.htm only}-->", "vars": {"ctx": "C"}, "files": {"child.htm": "{$ctx|default:\"无\"}"}, "expect": "无"},
  {"name": "template with only 不影响调用方", "tpl": "<!--{template child.htm with=[\"tmp\"=>\"in\"] only}-->[{$tmp|default:\"外\"}]", "files": {"child.htm": "{$tmp}"}, "expect": "in[外]"},
  {"name": "插件 page_links 基础", "plugins": ["pagination"], "tpl": "{$p|page_links:$tp,?page=%d}", "vars": {"p": 2, "tp": 3}, "expect": "<a href=\"?page=1\" class=\"page-prev\">&laquo;</a><a href=\"?page=1\">1</a><span class=\"page-current\">2</span><a href=\"?page=3\">3</a><a href=\"?page=3\" class=\"page-next\">&raquo;</a>"},
  {"name": "插件 page_links 省略号", "plugins": ["pagination"], "tpl": "{$p|page_links:$tp,?page=%d,1}", "vars": {"p": 5, "tp": 10}, "expect": "<a href=\"?page=4\" class=\"page-prev\">&laquo;</a><a href=\"?page=1\">1</a><span class=\"page-ellipsis\">&hellip;</span><a href=\"?page=4\">4</a><span class=\"page-current\">5</span><a href=\"?page=6\">6</a><span class=\"page-ellipsis\">&hellip;</span><a href=\"?page=10\">10</a><a href=\"?page=6\" class=\"page-next\">&raquo;</a>"},
  {"name": "插件 asset 外部 URL 原样", "plugins": ["asset"], "tpl": "{\"http://cdn.example.com/a.css\"|asset}", "expect": "http://cdn.example.com/a.css"},
  {"name": "插件 asset 不存在文件原样", "plugins": ["asset"], "tpl": "{\"no/such-file.css\"|asset:.}", "expect": "no/such-file.css"},
  {"name": "插件 asset 真实文件版本号", "plugins": ["asset"], "tpl": "{\"test/fixtures/asset/app.css\"|asset:\".\"}", "expect_pattern": "^test/fixtures/asset/app\\.css\\?v=\\d+$"},
  {"name": "插件 slug 英文", "plugins": ["text"], "tpl": "{\"Hello World!\"|slug}", "expect": "hello-world"},
  {"name": "插件 slug 中文保留", "plugins": ["text"], "tpl": "{\"你好 世界\"|slug}", "expect": "你好-世界"},
  {"name": "插件 excerpt 截断", "plugins": ["text"], "tpl": "{\"hello world foo\"|excerpt:5}", "expect": "hello…"},
  {"name": "插件 excerpt 不截短", "plugins": ["text"], "tpl": "[{\"hi\"|excerpt:5}]", "expect": "[hi]"},
  {"name": "插件 mask 手机号", "plugins": ["text"], "tpl": "{\"13812341234\"|mask:3,4}", "expect": "138****1234"},
  {"name": "插件 filesize KB", "plugins": ["number"], "tpl": "{1536|filesize}", "expect": "1.5 KB"},
  {"name": "插件 filesize B", "plugins": ["number"], "tpl": "{500|filesize}", "expect": "500 B"},
  {"name": "插件 money 货币", "plugins": ["number"], "tpl": "{1234.5|money:\"¥\"}", "expect": "¥1,234.50"},
  {"name": "插件 percent 百分比", "plugins": ["number"], "tpl": "{0.855|percent:1}", "expect": "85.5%"},
  {"name": "插件 nav_active 命中", "plugins": ["nav"], "tpl": "{\"/about\"|nav_active:on,/about/team}", "expect": "on"},
  {"name": "插件 nav_active 未命中", "plugins": ["nav"], "tpl": "[{\"/about\"|nav_active:on,/other}]", "expect": "[]"},
  {"name": "插件 nav_active 边界不误中", "plugins": ["nav"], "tpl": "[{\"/about\"|nav_active:on,/abouts}]", "expect": "[]"},
  {"name": "插件 query_merge 覆盖", "plugins": ["nav"], "tpl": "{\"page=1&s=x\"|query_merge:[\"page\"=>2]}", "expect": "page=2&s=x"},
  {"name": "插件 seo_meta 字面量", "plugins": ["seo"], "tpl": "<!--{seo_meta title=\"标题\" description=\"描述\"}-->", "expect": "<title>标题</title><meta name=\"description\" content=\"描述\">"},
  {"name": "插件 seo_meta 表达式", "plugins": ["seo"], "tpl": "<!--{seo_meta title=\"$t\"}-->", "vars": {"t": "Hello"}, "expect": "<title>Hello</title>"},
  {"name": "插件 seo_og", "plugins": ["seo"], "tpl": "<!--{seo_og title=\"T\" type=\"article\"}-->", "expect": "<meta property=\"og:title\" content=\"T\"><meta property=\"og:type\" content=\"article\">"},
  {"name": "插件 seo_jsonld", "plugins": ["seo"], "tpl": "<!--{seo_jsonld $d}-->", "vars": {"d": {"@type": "Thing"}}, "expect": "<script type=\"application/ld+json\">{\"@type\":\"Thing\"}</script>"},
  {"name": "未知指令原样保留", "tpl": "X<!--{custom-thing a=1}-->Y", "expect": "X<!--{custom-thing a=1}-->Y"},
  {"name": "CSS 花括号不误吞", "tpl": "<style>.a{color:red}</style>", "expect": "<style>.a{color:red}</style>"}
]