← 文档中心

使用指南

English | 中文

本文档提供 Zandy_Template 模板引擎的详细使用指南。

目录

安装和配置

安装

方式1:使用 Composer(推荐)

composer require zandy/php-template-engine

注意:

方式2:手动安装

  1. 下载 Template.php 文件
  2. 在代码中 require_once 'Template.php'
  3. 如需使用插件,手动 require_once 相应的插件文件

基本配置

基本配置

定界符可配置:4 个定界符常量支持在 require 引擎之前预定义覆盖 (ZANDY_TEMPLATE_DELIMITER_LOGIC_LEFT/RIGHT、VAR_LEFT/RIGHT)—— 方括号、花括号、[% %] 等任意合理组合,词法层自动消歧。 详见 syntax.md「定界符配置」。默认值无需任何设置。

需要设置 $GLOBALS['siteConf'] 配置:

$GLOBALS['siteConf'] = array(
    'tplBaseDir' => '/path/to/templates/base',      // 模板基础目录
    'tplCacheBaseDir' => '/path/to/cache',          // 缓存基础目录(HTML 缓存缺省也写入此目录;带不带尾斜杠均可)
    'cacheHTMLDir' => '/path/to/cache/html',        // 可选:HTML 缓存专用目录,未配置时回退到 tplCacheBaseDir
    'tplDir' => '/path/to/templates',               // 当前模板目录
);

配置说明

快速开始

基本使用

// 如果使用 Composer
require_once 'vendor/autoload.php';

// 如果手动安装
require_once 'Template.php';

// 配置
$GLOBALS['siteConf'] = array(
    'tplBaseDir' => '/path/to/templates/base',
    'tplCacheBaseDir' => '/path/to/cache',
    'tplDir' => '/path/to/templates',
);

// 方式1:返回 HTML 字符串(推荐)
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);
echo $html;

// 方式2:直接 include(直接显示结果)
include Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);

变量传递方式

模板引擎支持三种变量传递方式,可根据安全需求选择:

方式1:完全开放模式(默认,向后兼容)

// 使用全局变量(最简单,向后兼容)
$GLOBALS['user'] = $user;
$GLOBALS['data'] = $data;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);

特点:

方式2:白名单模式(推荐用于生产环境)

// 配置白名单,只允许指定的变量被模板访问
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data', 'items'];

// 使用方式不变
$GLOBALS['user'] = $user;
$GLOBALS['data'] = $data;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);

特点:

方式3:显式传递模式(最安全)

模板间传参(v1.12.0):template 指令支持 with= 传参与 only 隔离—— <!--{template child.htm with=["k"=>$v]}-->(继承上下文 + with 覆盖)、 <!--{template child.htm with=[...] only}-->(只传 with 不继承)、 <!--{template child.htm only}-->(空上下文隔离包含)。 详见 syntax.md「template 传参」。

方式3.1:按需插件(v1.12.0)

六件功能插件不进 builtin 自动加载链,按需显式引入:

require_once 'plugins/pagination.php';  // 分页 page_links
require_once 'plugins/asset.php';       // 资源版本号 asset
require_once 'plugins/text.php';        // slug/excerpt/mask
require_once 'plugins/number.php';      // filesize/money/percent
require_once 'plugins/nav.php';         // nav_active/query_merge
require_once 'plugins/seo.php';         // seo_meta/seo_og/seo_jsonld
// 显式传递变量,完全控制变量访问
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
    'user' => $user,
    'data' => $data,
    'items' => $items
]);

特点:

配置说明

通过 $GLOBALS['siteConf']['template_vars_mode'] 配置变量提取模式:

注意:

使用场景

场景1:面向过程使用(文件顶层)

<?php
// index.php - 文件顶层
require_once 'Template.php';

$tplDir = '/path/to/templates/';
$cacheDir = '/path/to/cache/';

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

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

场景2:函数内部使用

<?php
// functions.php
function renderUserProfile($userId) {
    $tplDir = '/path/to/templates/';
    $cacheDir = '/path/to/cache/';
    
    // 获取数据(局部变量)
    $user = getUserById($userId);
    $posts = getUserPosts($userId);
    $stats = getUserStats($userId);
    
    // 推荐:显式传递(避免污染全局变量)
    return Zandy_Template::outString('user_profile.htm', $tplDir, $cacheDir, false, [
        'user' => $user,
        'posts' => $posts,
        'stats' => $stats
    ]);
}

场景3:类方法内部使用

<?php
// Controller.php
class UserController {
    private $tplDir = '/path/to/templates/';
    private $cacheDir = '/path/to/cache/';
    
    public function showProfile($userId) {
        // 获取数据(局部变量)
        $user = $this->getUserById($userId);
        $posts = $this->getUserPosts($userId);
        
        // 推荐:显式传递
        return Zandy_Template::outString('user_profile.htm', $this->tplDir, $this->cacheDir, false, [
            'user' => $user,
            'posts' => $posts
        ]);
    }
    
    public function renderProfile($userId) {
        // 使用 includeTemplate()(适合直接输出)
        $user = $this->getUserById($userId);
        $posts = $this->getUserPosts($userId);
        
        Zandy_Template::includeTemplate('user_profile.htm', $this->tplDir, $this->cacheDir, false, [
            'user' => $user,
            'posts' => $posts
        ]);
    }
}

场景4:outCache() + include 的使用

<?php
// 面向过程使用
$GLOBALS['user'] = $user;
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract(Zandy_Template::getTemplateVars());  // 使用配置模式
include $cacheFile;

// 函数内部使用(推荐)
function renderPage() {
    $user = getUser();
    
    // 方式1:使用 includeTemplate()(最推荐)
    Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir, false, [
        'user' => $user
    ]);
    
    // 方式2:使用 getTemplateVars() 辅助函数
    $cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
    extract(Zandy_Template::getTemplateVars(['user' => $user]));
    include $cacheFile;
}

场景5:使用模板测试(Tests)语法

<!-- user_list.htm -->
<!--{if $users is array and is not empty}-->
    <ul>
        <!--{loop $users as $user}-->
            <li>
                <!--{if $user is not null}-->
                    <strong>{$user['name']}</strong>
                    <!--{if $user['email'] is not empty}-->
                        <span>{$user['email']}</span>
                    <!--{/if}-->
                <!--{else}-->
                    <em>用户不存在</em>
                <!--{/if}-->
            </li>
        <!--{/loop}-->
    </ul>
<!--{elseif $users is null}-->
    <p>数据加载失败</p>
<!--{else}-->
    <p>暂无用户</p>
<!--{/if}-->

说明:

场景6:使用宏定义(Macros)

<!-- 定义宏:格式化日期 -->
<!--{macro name="formatDate" date="" format="Y-m-d"}-->
    <span class="date">{echo date($format, strtotime($date))}</span>
<!--{/macro}-->

<!-- 定义宏:显示用户信息卡片 -->
<!--{macro name="userCard" user="" showEmail="true"}-->
    <div class="user-card">
        <h3>{$user['name']}</h3>
        <!--{if $showEmail == "true"}-->
            <p>{$user['email']}</p>
        <!--{/if}-->
    </div>
<!--{/macro}-->

<!-- 调用宏:使用字符串参数 -->
<p>发布日期:<!--{call name="formatDate" date="2026-01-15" format="Y-m-d H:i:s"}--></p>

<!-- 调用宏:使用变量参数 -->
<p>发布日期:<!--{call name="formatDate" date="$postDate" format="Y-m-d"}--></p>

<!-- 调用宏:多个参数 -->
<!--{call name="userCard" user="$currentUser" showEmail="false"}-->

<!-- 在循环中使用宏 -->
<!--{loop $users as $user}-->
    <!--{call name="userCard" user="$user" showEmail="true"}-->
<!--{/loop}-->

使用前需要加载插件:

require_once 'plugins/macros.php';

说明:

最佳实践

1. 变量传递

推荐:

不推荐:

1.1 插件加载说明

1.2 调试与 PHP 能力语法

2. outCache 场景

推荐:

不推荐:

3. 模板测试(Tests)语法

推荐:

示例:

<!-- ✅ 推荐:使用模板测试语法 -->
<!--{if $items is array and is not empty}-->
    <!-- 处理数组 -->
<!--{/if}-->

<!-- ❌ 不推荐:混合写法(不支持) -->
<!--{if $items is array && !empty($items)}-->
    <!-- 这种写法会导致语法错误 -->
<!--{/if}-->

不推荐:

4. 宏定义(Macros)

推荐:

示例:

<!-- ✅ 推荐:定义可复用的宏 -->
<!--{macro name="userCard" user="" showEmail="true"}-->
    <div class="user-card">
        <h3>{$user['name']}</h3>
        <!--{if $showEmail == "true"}-->
            <p>{$user['email']}</p>
        <!--{/if}-->
    </div>
<!--{/macro}-->

<!-- 在循环中使用宏 -->
<!--{loop $users as $user}-->
    <!--{call name="userCard" user="$user"}-->
<!--{/loop}-->

不推荐:

4. 安全配置

开发环境:

// 可以使用完全开放模式(默认),方便调试
// 无需额外配置

生产环境:

// 推荐使用白名单模式
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data', 'items'];

高安全要求:

// 使用显式传递模式
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
    'user' => $user,
    'data' => $data
]);

4. HTML 转义和 XSS 防护

转义策略:

使用场景:

  1. 用户输入(必须转义):

    <!-- ✅ 正确:转义用户输入,防止 XSS 攻击 -->
    用户名:{$username|escape}
    评论:{$comment|escape}
    搜索关键词:{$keyword|escape}
  2. 系统内容(可不转义):

    <!-- ✅ 可以:系统生成的内容 -->
    标题:{$title}
    描述:{$description}
  3. 过滤器链:

    <!-- 可以组合多个过滤器 -->
    {$username|upper|escape}              <!-- 先转大写,再转义 -->
    {$description|truncate:50|escape}    <!-- 先截断,再转义 -->

安全提示:

5. 模板来源不可信

如果模板来源不可信,必须:

  1. 使用显式传递模式
  2. 禁用 PHP 代码块(如果可能)
  3. 严格验证模板路径
  4. 所有用户输入必须转义(使用 |escape)

更多信息