← 文档中心

API 参考

English | 中文

本文档提供 Zandy_Template 模板引擎的完整 API 参考。

目录

outString()

返回填充数据后的 HTML 字符串(推荐)

语法

public static function outString(
    string $tplFileName, 
    string $tplDir = '', 
    string $cacheDir = '', 
    bool $forceRefreshCache = false, 
    array|null $vars = null
): string

参数

返回值

返回填充数据后的 HTML 字符串。

使用示例

// 方式1:使用全局变量(向后兼容)
$GLOBALS['user'] = $user;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);
echo $html;

// 方式2:显式传递变量(推荐,更安全)
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
    'user' => $user,
    'data' => $data
]);
echo $html;

// 方式3:配置白名单模式
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data'];
$GLOBALS['user'] = $user;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);

outCache()

返回编译后的缓存文件路径,然后 include

语法

public static function outCache(
    string $tplFileName, 
    string $tplDir = '', 
    string $cacheDir = '', 
    bool $forceRefreshCache = false
): string|false

参数

返回值

返回编译后的缓存文件路径,失败返回 false。

使用示例

// 方式1:使用 includeTemplate()(推荐,支持安全模式)
Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir, false, ['user' => $user]);

// 方式2:手动 include(需要手动处理变量)
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract(Zandy_Template::getTemplateVars(['user' => $user]));
include $cacheFile;

// 方式3:使用全局变量(向后兼容,但不推荐)
$GLOBALS['user'] = $user;
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract($GLOBALS);  // ⚠️ 安全问题
include $cacheFile;

includeTemplate()

安全地 include 模板文件(推荐用于 outCache 方式)

语法

public static function includeTemplate(
    string $tplFileName, 
    string $tplDir = '', 
    string $cacheDir = '', 
    bool $forceRefreshCache = false, 
    array|null $vars = null
): void

参数

返回值

无返回值,直接输出模板内容。

使用示例

// 方式1:使用全局变量(向后兼容)
$GLOBALS['user'] = $user;
Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir);

// 方式2:显式传递变量(推荐,更安全)
Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir, false, ['user' => $user]);

// 方式3:配置白名单模式
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data'];
$GLOBALS['user'] = $user;
Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir);

includeCompiledWithVars()

带显式变量包含编译产物(v1.12.0,template with= 传参的运行时支撑)

语法

public static function includeCompiledWithVars(
    string $compiledFile,
    array $vars
): mixed

参数

返回值

include 返回值(失败 false)。

说明

在独立作用域 extract(EXTR_SKIP 保护本方法参数名)后 include—— 传入变量不泄漏到调用方作用域。template 指令的 with=/only 即构建于 此方法之上;一般用于需要"显式变量集 + 隔离包含"的自定义场景。

validate()

结构诊断(不 halt):收集全部模板结构错误,返回消息数组。

语法

public static function validate(string $template): array

参数

返回值

array - 诊断消息列表(合法模板返回空数组)

使用示例

$diags = Zandy_Template::validate($tpl);
foreach ($diags as $msg) {
    echo $msg, "\n";
}

validateDetailed()

结构化结构诊断(v1.13.0):在 validate() 基础上为每条诊断附加错误码、 行号、修复建议与源码片段,便于 IDE 插件与 CI 集成消费。

语法

public static function validateDetailed(string $template): array

参数

返回值

array - 诊断列表,每项字段:

字段 类型 说明
code string 错误码(见下表)
level string error
line int 模板行号(无法提取时为 0)
message string 原始诊断消息(与 validate() 一致)
suggestion string 修复建议
snippet string 出错行源码片段(超 160 字符截断加 …)

错误码表:

错误码 含义
ZTE101 未闭合块
ZTE102 多余闭合
ZTE103 交错嵌套
ZTE104 分支位置(elseif/else/重复 else)
ZTE105 循环空态挂靠
ZTE106 switch 子块位置
ZTE107 重复 default
ZTE100 其他结构错误

使用示例

foreach (Zandy_Template::validateDetailed($tpl) as $d) {
    printf("[%s] 第 %d 行:%s\n  建议:%s\n", $d['code'], $d['line'], $d['message'], $d['suggestion']);
}

getRegisteredDirectives() / getRegisteredFunctions() / getRegisteredValidators()

扩展协议内省 API(v1.11.0):读取当前进程已注册的插件表——插件清单 展示、调试与宿主集成使用。

语法

public static function getRegisteredDirectives(): array   // array('before'=>[名=>handler], 'after'=>[...])
public static function getRegisteredFunctions(): array    // 同上
public static function getRegisteredValidators(): array   // array(callable, ...)

返回值

协议版本常量

Zandy_Template::ZTE_EXTENSION_PROTOCOL_VERSION; // '1.0'

使用示例

foreach (array_keys(Zandy_Template::getRegisteredFunctions()['after']) as $name) {
    echo $name, "\n";   // upper / lower / escape / ...
}

mapCompiledLine()

编译产物行号 → 模板行号(v1.14.0 运行时错误定位)

语法

public static function mapCompiledLine(int $compiledLine, array|null $sourceMap = null): ?int

参数

返回值

int|null - 模板行号;无映射返回 null(精确未命中时向前找最近映射行)

使用示例

try {
    Zandy_Template::outString('page.htm', $tplDir, $cacheDir);
} catch (Throwable $e) {
    $tplLine = Zandy_Template::mapCompiledLine($e->getLine());
    echo "模板第 ", var_export($tplLine, true), " 行出错: ", $e->getMessage();
}

自动模式:siteConf['tpl_error_map'] = true 时(PHP 7+), outString 自动完成上述映射并抛出 Zandy_Template_RuntimeException ——异常对象带 templateFile / templateLine 属性,消息前缀含 "(模板第 N 行)";原始异常保留在 getPrevious()。

getTemplateVars()

安全地提取模板变量(用于 outCache + include 方式)

语法

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

参数

返回值

返回提取的变量数组。

使用示例

// 方式1:显式传递变量(推荐)
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract(Zandy_Template::getTemplateVars(['user' => $user]));
include $cacheFile;

// 方式2:使用配置模式
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data'];
$GLOBALS['user'] = $user;
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract(Zandy_Template::getTemplateVars());  // 使用配置的白名单
include $cacheFile;

out()

通用输出方法,可指定输出模式

语法

public static function out(
    string $tplFileName, 
    string $tplDir = '', 
    string $cacheDir = '', 
    bool $forceRefreshCache = false, 
    int $cacheMod = ZANDY_TEMPLATE_CACHE_MOD_PHPC
): string|false

参数

返回值

根据缓存模式返回不同的值(见缓存模式常量说明)。

使用示例

// 返回 HTML 内容
$html = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_HTML_CONTENTS);

// 返回缓存文件路径
$cacheFile = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_PHPC);

// 返回可 eval 的字符串
$code = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_EVAL);
eval($code);

outHTML()

返回 HTML 文件路径或内容

语法

public static function outHTML(
    string $tplFileName, 
    string $tplDir = '', 
    string $cacheDir = '', 
    bool $forceRefreshCache = false, 
    int $outMod = ZANDY_TEMPLATE_CACHE_MOD_HTML, 
    array|null $vars = null
): string|false

参数

返回值

根据输出模式返回 HTML 文件路径或内容。

使用示例

// 返回 HTML 文件路径
$htmlFile = Zandy_Template::outHTML('template.htm', $tplDir, $cacheDir);

// 返回 HTML 内容
$htmlContent = Zandy_Template::outHTML('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_HTML_CONTENTS);

outEval()

返回可 eval 的字符串

语法

public static function outEval(string $tplFileName, string $tplDir = ''): string|false

参数

返回值

返回可 eval 的字符串,失败返回 false。

使用示例

$code = Zandy_Template::outEval('template.htm', $tplDir);
if ($code !== false) {
    ob_start();
    eval($code);
    $result = ob_get_clean();
    echo $result;
}

check_syntax()

检查编译产物(PHP 文件)的语法是否正确

语法

public static function check_syntax(string $filename, string $tplName = '', bool $unlinkOnFailure = false): bool

参数

返回值与失败契约

使用示例

$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
$result = Zandy_Template::check_syntax($cacheFile, 'template.htm');
// 能执行到这里即语法正确($result === true);语法错误已在内部 halt

缓存模式常量

ZANDY_TEMPLATE_CACHE_MOD_PHPC (1)

返回编译后的 PHP 文件路径

$cacheFile = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_PHPC);
include $cacheFile;

ZANDY_TEMPLATE_CACHE_MOD_HTML (2)

返回 HTML 文件路径

$htmlFile = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_HTML);

ZANDY_TEMPLATE_CACHE_MOD_EVAL (4)

返回可 eval 的字符串

$code = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_EVAL);
eval($code);

ZANDY_TEMPLATE_CACHE_MOD_HTML_CONTENTS (8)

返回 HTML 内容

$html = Zandy_Template::out('template.htm', $tplDir, $cacheDir, false, ZANDY_TEMPLATE_CACHE_MOD_HTML_CONTENTS);
echo $html;

插件系统

registerDirective()

注册自定义指令插件

语法

public static function registerDirective(
    string $name, 
    callable $handler, 
    string $position = 'after'
): void

参数

返回值

无返回值。

使用示例

// 注册自定义指令(单行语法,参考 examples/plugin_demo.php 的 when 实现)
Zandy_Template::registerDirective('when', function($content, $params, $context) {
    $EOB = $context['EOB'];
    // $params 是开始标签中的参数部分(如 "$user->isAdmin()")
    // 参考内置 if:先关闭当前 heredoc,再开始 if 块
    return "\r\n$EOB;\r\nif ($params) {echo <<<$EOB\r\n";
}, 'after');

// 使用自定义指令
// 模板:<!--{when $user->isAdmin()}-->

registerFunction()

注册自定义函数插件(过滤器)

语法

public static function registerFunction(
    string $name, 
    callable $handler, 
    string $position = 'after'
): void

参数

返回值

无返回值。

使用示例

// 注册自定义过滤器
Zandy_Template::registerFunction('upper', function($value, $params = '') {
    return "strtoupper($value)";
}, 'after');

// 使用自定义过滤器
// 模板:{$var|upper}

registerValidator()

注册插件验证回调(用于验证指令结构完整性)

语法

public static function registerValidator(callable $validator): void

参数

返回值

无返回值。

使用示例

// 注册验证回调
Zandy_Template::registerValidator(function($template) {
    // 检查 when/else-when/end-when 结构
    $whenCount = preg_match_all('/<!--\{when\s+/i', $template);
    $endWhenCount = preg_match_all('/<!--\{end-when\}/i', $template);
    if ($whenCount !== $endWhenCount) {
        Zandy_Template::halt('when 指令结构不完整:when 和 end-when 数量不匹配', true);
    }
});

setValidationEnabled()

设置是否启用指令结构验证

语法

public static function setValidationEnabled(bool $enable): void

参数

返回值

无返回值。

使用示例

// 启用验证(默认)
Zandy_Template::setValidationEnabled(true);

// 禁用验证(生产环境可关闭以提高性能)
Zandy_Template::setValidationEnabled(false);

isValidationEnabled()

获取当前验证状态

语法

public static function isValidationEnabled(): bool

返回值

返回当前验证是否启用(true 启用,false 禁用)。

使用示例

$isEnabled = Zandy_Template::isValidationEnabled();
if ($isEnabled) {
    echo "验证已启用";
}

loadBuiltinPlugins()

加载内置插件

语法

public static function loadBuiltinPlugins(): bool

参数

无参数。

返回值

bool——插件文件存在并加载成功返回 true,否则返回 false。

使用示例

// 加载所有内置插件
require_once 'plugins/builtin.php';
// 或
Zandy_Template::loadBuiltinPlugins();

内置插件包括:

静态 API 退役时间线(v1.9 起)

阶段 版本 状态
共存期开始 v1.9.0 实例化 API 上线(Zandy_Template_Engine),静态 API 全保留
退役标记 v1.9.0 提前入库,v1.10 起生效 静态编译/渲染入口 docblock 标记 @deprecated(IDE/静态分析可见,不删除、无运行时变化)
移除 v2.0.0 删除静态入口(触发判据制:实例化 API 稳定运行足够久 + 移除必要性成立)

Engine 委托方法清单

实例 API 与静态 API 方法对齐(v1.14.0 补齐):渲染 out/outString/outHTML/outCache/ outEval/includeTemplate/includeCompiledWithVars;编译 parse/validate/validateDetailed/ check_syntax;诊断 audit/mapCompiledLine/getLastSourceMap;插件 registerDirective/ registerFunction/registerValidator/loadBuiltinPlugins/getRegistered*;策略 checkExpressionAllowed;变量 getTemplateVars/set。全部按 withSiteConf 模式委托。

被标记入口:parse / out / outCache / outString / outHTML / outEval / includeTemplate / getTemplateVars / loadBuiltinPlugins / check_syntax。 迁移方式见 syntax.md 实例化 API 章节。

更多信息