Template Syntax Reference
This document is the complete syntax reference for the Zandy_Template template engine.
Contents
- Delimiter Rules
- Variable Output
- Loops
- Conditionals
- Switch Statement
- Template Inheritance
- Macro Definitions
- Template Inclusion
- File Inclusion
- Expressions and PHP Code
- Time Functions
- PHP Constants
- Language Packs
- Template Comments
Delimiter Rules
Logic Control Statements
Use <!--{ }--> (wrapped in an HTML comment, so browser previews keep the page structure intact)
Applies to:
if,for,foreach,loop,switchtemplate,include,include_oncephp,set
Example:
<!--{if $condition}-->
<!--{loop $items as $item}-->
<!--{template header.htm}-->Variable Output
Use { } (concise, does not break the structure)
Applies to:
{$var},{$array['key']}{time},{now},{date}{echo},{LANG}
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:
- When LOGIC and VAR share the same shape (e.g. both
{ }), braces in static text must be balanced (an unbalanced{is treated as a broken tag; balanced braces that are neither a directive name nor an output form — CSS/JS — stay static and are unaffected) - When a logic tag body's first word looks exactly like an output form (starts with
$,time/now/date/echo/LANG, or an ALL-UPPERCASE constant), it takes effect as output — avoid these shapes when naming plugin directives - The chained expression / trailing condition of the
istest syntax must not contain the first character of the right delimiter (default}— same as the historical behavior of the default combo)
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:
- Default behavior: no escaping (kept backward compatible)
- Automatic escaping: enabled with the config
$GLOBALS['siteConf']['auto_escape'] = true - Manual escaping: add the
|escapemodifier by hand wherever escaping is needed - Disabling escaping: the
|rawfilter turns automatic escaping off
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:
User input (must be escaped):
<!-- ✅ correct: escape user input --> 用户名:{$username|escape} 评论:{$comment|escape} 搜索关键词:{$keyword|escape}System content (may stay unescaped):
<!-- ✅ acceptable: system-generated content --> 标题:{$title} 描述:{$description}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}produceshtmlspecialchars(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:
Enabling automatic escaping:
$GLOBALS['siteConf']['auto_escape'] = true;- once enabled, every
{$var}(no filter) is escaped automatically - every
{$var|filter}(has filters but neitherescapenorraw) gets escaping added automatically {$var|raw}disables automatic escaping
- once enabled, every
Explicitly disabling automatic escaping:
$GLOBALS['siteConf']['auto_escape'] = false;- turns automatic escaping off explicitly; the behavior is the same as not setting it
Not set (default):
- when
auto_escapeis not set, automatic escaping is off by default (backward compatible)
- when
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:
- provided by the
filtersplugin - implementation:
htmlspecialchars($var, ENT_QUOTES, 'UTF-8') - the
rawfilter disables automatic escaping
Security notes:
- ⚠️ user input must always be escaped to prevent XSS attacks
- ✅ system content may stay unescaped, but make sure the content itself is safe
- 🔒 enabling automatic escaping is recommended:
$GLOBALS['siteConf']['auto_escape'] = true - 📖 for more security advice see the Security Guide
literal Block
Syntax
<!--{literal}-->
此处内容逐字呈现:{$var}、<!--{if $x}-->、{$a|filter} 等模板语法
一律不解析、不插值,适合展示模板语法本身或嵌入 JS 模板字符串。
<!--{/literal}-->Description
- literal content is emitted through nowdoc isolation with zero escaping loss (
$, backslashes and{are rendered as-is) - block-stack pairing validation covers literal//literal (a missing closing tag reports the template line number at compile time)
- sandbox mode and compile switches such as strict_variables are covered in "Compile Switches" below
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 diagnosticstplDir/cacheDirare instance convenience keys:cacheDirmaps to siteConf'stplCacheBaseDir(whentplCacheBaseDiris not explicitly configured,rtrim(cacheDir, '/') . '/'is used; an empty string counts as unconfigured and falls back to the existing siteConf), andtplDirmaps totplBaseDir(its parent directory) — there is nocacheDirkey at the siteConf level; the native cache-side key istplCacheBaseDir(outHTML additionally falls back tocacheHTMLDir)- the remaining config keys match siteConf (auto_escape/tpl_sandbox/tpl_strict_variables/template_vars_mode, etc.)
- when the host has not taken the
Engineclass name it is aliased automatically, sonew Engine([...])works directly - the whole static API stays available and compatible (both tracks coexist); instance config is layered over siteConf at runtime and restored automatically on exit
- since v1.10 the static compile/render entry points (parse/out/outCache/outString, etc.) are marked @deprecated: annotation only (visible to IDEs and static analyzers), nothing removed and no runtime behavior change; they are removed in v2.0
autoescape Context Escaping Block
<script>var s = <!--{autoescape js}-->{$userInput}<!--{/autoescape}-->;</script>
<a href="?q=<!--{autoescape url}-->{$q}<!--{/autoescape}-->">- contexts:
js(the full json_encode HEX set) /url(rawurlencode) /css(allowlist character filtering) /html(htmlspecialchars) - variable output inside the block is escaped for the context and takes precedence over auto_escape/strict_variables; the context must be one of the four (otherwise the template line number is reported at compile time, and
validate()reports it too) {LANG}and<!--{trans}-->output inside the block (including trans placeholder values) is context-escaped as well- when the filter chain already contains an explicit
|escapeor|raw, context escaping is not applied again ({$v|escape}is not escaped twice)
trans i18n Pluralization Block
<!--{trans key="apples" count="$n" zero="无苹果" one="1 apple" other="%d apples"}-->- the language pack ($_LANG) key is looked up first; on a hit the
%dplaceholders are replaced with count; on a miss it falls back to the zero/one/other forms (the count expression can be any PHP expression)
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):
<!--{loop $arr AS $key => $value}-->- with AS and =><!--{loop $arr AS $key $value}-->- with AS plus key and value<!--{loop $arr AS $value}-->- with AS and value<!--{loop $arr $key => $value}-->- with =><!--{loop $arr $key $value}-->- with key and value<!--{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:
$_zte_loop->index- current index (starts at 0)$_zte_loop->iteration- current iteration number (starts at 1)$_zte_loop->first- whether this is the first iteration (boolean)$_zte_loop->last- whether this is the last iteration (boolean)$_zte_loop->length- total array length$_zte_loop->even- whether the index is even (boolean, for alternating styles)$_zte_loop->odd- whether the index is odd (boolean, for alternating styles)$_zte_loop->remaining- iterations remaining$_zte_loop->parent- parent loop object (in nested loops; null for the outermost level)
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 |
istests 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:
andis the same as&&,oris the same as||- the second test may omit the variable and reuses the variable of the first test automatically
- the
is notnegative form is supported
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
An ordinary PHP expression (including function calls) may follow an
istest 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)}-->Compile-time translation:
istest syntax is translated into a standard PHP expression at compile time, with zero runtime overheadMixing with standard PHP expressions: an
istest must sit at the start of the statement; after it, any ordinary expression may follow, joined withand/or/&&/||(parenthesized groups included)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.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
switchandcaseaccept expressions, e.g.<!--{switch $x + 1}-->,<!--{case $y * 2}-->- the
switchexpression supports one level of nested parentheses (e.g.<!--{switch strtolower($x)}-->); two or more levels of nesting are not supported yet break-caseprovides fall-through: after the break, execution continues with the next casebreak-defaultprovides fall-through: after the break, execution continues with defaultbreakexits the current casecontinuehas no effect inside switch; it is meant for loops only- before the first
case/defaultonly whitespace is allowed (it is ignored automatically); output content or other directives there are reported at compile time (no illegal PHP is generated), andvalidate()reports the structural problem as well - an empty switch (no case at all) is legal and simply outputs the surrounding content
- a
break-case/break-defaultwritten as the first branch of a switch degrades to a normalcase/default(there is no preceding branch to break out of)
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:
- the
extendsdirective must be on the first line of the template (a UTF-8 BOM is stripped automatically and does not break this check) - text content before
extendsis reported at compile time (the legacy implementation silently ignored inheritance and dropped block content) - relative and absolute paths are supported
- string literals are supported:
<!--{extends 'base.htm'}-->or<!--{extends "base.htm"}-->
block Directive
Defines an overridable content block:
<!--{block name="content"}-->
默认内容
<!--{/block}-->Notes:
- the
nameattribute sets the block name - a block may carry default content (used when the child template does not override it)
appendandprependmodes are supported
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
- extends position: the
extendsdirective must be on the first line of the template (whitespace and comments are ignored) - block names: block names must be unique within a template
- parent call: only valid inside a block, never outside one
- performance: multi-level inheritance increases parse time; no more than 3 levels is recommended
- cyclic inheritance detection: cycles are detected and blocked automatically
More information:
- design document: Template inheritance design
- example code:
examples/template_inheritance_demo.php - unit tests:
test/TemplateInheritanceTest.php
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:
key: cache key (required); a string literal or a variable (e.g.$cacheKey)time: cache lifetime (optional), in seconds, 3600 seconds (1 hour) by default; a number or a variable (e.g.$cacheTime)if: condition expression (optional); the content is cached only when the condition is true, otherwise it runs directlytags: cache tags (optional), comma-separated, used for bulk cache clearing (e.g."user,profile")depends: cache dependency (optional); when the dependency value changes the cache is invalidated automatically (e.g.$userVersion)
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 10KBEnable 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
- cache directory: cache files are stored in "
/fragments/" — the base directory is the explicitly passed $cacheDirargument, falling back to siteConf'stplCacheBaseDirwhen empty (thecacheDirconvenience key on an Engine instance maps to the same key) - cache key uniqueness: make sure different templates use different cache keys to avoid collisions
- dependency changes: when the
dependsattribute value changes, the cache is invalidated automatically - conditional caching: when the
ifcondition is false, the content still runs but is not cached - nested caching: multiple levels are supported; inner caches are independent of outer ones
- performance: cache key computation is already optimized — the fixed part is computed at compile time
More information:
- design document: Fragment cache design analysis
- optimization notes: Fragment cache improvement plan
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.htmInside 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:
- if
$_LANG['title']exists, its value is output - if it does not exist and debug mode is on,
#title#is output - otherwise
titleis output
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:
custom-loop- custom loop directiveswhen/else-when/end-when- conditional directivesdate-format- date formatting filterdebug-info- debug information filterfilters- common filters (upper, lower, escape, truncate, default, nl2br, date)
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):
- Loop bodies with static text or
{$var}output directives both nest fully — custom-loop has migrated to contract v2 (handlers receive text/PHP mixed segments joined viamixSegmentsToPhp()), so output directives inside nested loop bodies work completely (the legacy heredoc text-wrapping limitation is resolved) - Legacy-contract (v1, string content) plugins remain limited in the nested
+output form — migrating to contract v2 removes the limitation
(locking tests:
test/ContractV2Test.php; NestedBlockPluginTest case 9 is a positive assertion)
Custom Plugins
Custom directive and function plugins can be registered; see the Plugin development guide and the API reference.
More Information
- Usage guide - detailed usage instructions and best practices
- API reference - complete API documentation
- Security guide - secure usage guide
- Performance guide - performance recommendations and best practices
Loop else Semantics
<!--{loop-else}-->/<!--{foreach-else}-->: the else branch runs when the array is empty (classic semantics)<!--{for-else}-->: for loops have no else semantics — the tag is treated as the end of the loop, and whatever follows is output after the loop finishes (earlier versions failed to compile; the form is supported now)
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 -->- context inheritance: aside from with, the child template still inherits every variable in the caller's scope (exactly as it does without with)
- override wins: when a with key collides with a context variable, the with value wins
- scope isolation: variables injected by with are valid only inside the child template and never leak back to the caller (an isolated-scope include)
- the with expression is passed straight through to PHP, but must not contain
}(it collides with the directive delimiter) — pass complex expressions such as closures in through a variable - only modifier (trailing keyword):
with=[...] onlypasses only the with values and does not inherit the caller's context; a bareonly(no with) = an empty-context isolated include — useful for componentization (the child sees only the explicitly passed data)
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>macrodefines a macro:nameis the macro name, the remaining attributes are parameters with defaultscallinvokes it: pass arguments as same-named attributes (values may be PHP expressions such as"$postDate")- Macro registry is per template file; define before calling
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 -->-sits directly against the delimiter (<!--{-and-}-->); once stripped, the directive body parses normally- left trim only cuts the tail of static text (it never wrongly cuts the heredoc structure of the compiled artifact)
- right trim is consumed by the first static segment after the tag (when another directive/output follows immediately there is no whitespace to cut and it silently has no effect)
- the output syntax
{...}does not support trim markers (it is ambiguous with the subtraction-); the closing tags of php/literal blocks do not support them either
Syntax Cheat Sheet (Executable Specification)
This table is a machine-readable syntax specification (docs as tests, #31):
test/DocAsTest.phpcompiles 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": "<b>"},
{"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": "<b>"},
{"name": "过滤器链 upper|escape", "tpl": "{$s|upper|escape}", "vars": {"s": "<x>"}, "expect": "<X>"},
{"name": "auto_escape 开启(默认转义)", "tpl": "{$s}", "vars": {"s": "<b>"}, "siteConf": {"auto_escape": true}, "expect": "<b>"},
{"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\">«</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\">»</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\">«</a><a href=\"?page=1\">1</a><span class=\"page-ellipsis\">…</span><a href=\"?page=4\">4</a><span class=\"page-current\">5</span><a href=\"?page=6\">6</a><span class=\"page-ellipsis\">…</span><a href=\"?page=10\">10</a><a href=\"?page=6\" class=\"page-next\">»</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>"}
]