← Documentation

Usage Guide

This document provides a detailed usage guide for the Zandy_Template template engine.

Table of Contents

Installation and Configuration

Installation

Option 1: Using Composer (recommended)

composer require zandy/php-template-engine

Note:

Option 2: Manual installation

  1. Download the Template.php file
  2. require_once 'Template.php' in your code
  3. To use plugins, require_once the corresponding plugin files manually

Basic Configuration

Delimiter Configuration

The 4 delimiter constants (ZANDY_TEMPLATE_DELIMITER_LOGIC_LEFT/RIGHT, VAR_LEFT/RIGHT) can be pre-defined before requiring the engine — square brackets, braces, [% %], any reasonable combination with automatic lexical disambiguation. See "Delimiter Configuration" in syntax.en.md. Defaults require no configuration.

The $GLOBALS['siteConf'] configuration must be set:

$GLOBALS['siteConf'] = array(
    'tplBaseDir' => '/path/to/templates/base',      // template base directory
    'tplCacheBaseDir' => '/path/to/cache',          // cache base directory (HTML cache is also written here by default; with or without a trailing slash)
    'cacheHTMLDir' => '/path/to/cache/html',        // optional: dedicated directory for HTML cache, falls back to tplCacheBaseDir when unset
    'tplDir' => '/path/to/templates',               // current template directory
);

Configuration Reference

Quick Start

Basic Usage

// If using Composer
require_once 'vendor/autoload.php';

// If installed manually
require_once 'Template.php';

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

// Option 1: return an HTML string (recommended)
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);
echo $html;

// Option 2: include directly (displays the result immediately)
include Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);

Variable Passing Methods

The template engine supports three variable passing methods, which you can choose from according to your security needs:

Method 1: Fully open mode (default, backward compatible)

// Use global variables (simplest, backward compatible)
$GLOBALS['user'] = $user;
$GLOBALS['data'] = $data;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);

Characteristics:

// Configure a whitelist so only the specified variables can be accessed by the template
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data', 'items'];

// Usage stays the same
$GLOBALS['user'] = $user;
$GLOBALS['data'] = $data;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);

Characteristics:

Method 3: Explicit passing mode (most secure)

Passing arguments between templates (v1.12.0): the template directive supports with= argument passing and only isolation— <!--{template child.htm with=["k"=>$v]}--> (inherited context + with overrides), <!--{template child.htm with=[...] only}--> (pass only with, no inheritance), <!--{template child.htm only}--> (empty-context isolated inclusion). See "template argument passing" in syntax.md.

Method 3.1: On-demand plugins (v1.12.0)

The six feature plugins are not part of the builtin auto-load chain; include them explicitly on demand:

require_once 'plugins/pagination.php';  // pagination page_links
require_once 'plugins/asset.php';       // asset versioning asset
require_once 'plugins/text.php';        // slug/excerpt/mask
require_once 'plugins/number.php';      // filesize/money/percent
require_once 'plugins/nav.php';         // nav_active/query_merge
require_once 'plugins/seo.php';         // seo_meta/seo_og/seo_jsonld
// Pass variables explicitly for full control over variable access
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
    'user' => $user,
    'data' => $data,
    'items' => $items
]);

Characteristics:

Configuration Reference

The variable extraction mode is configured through $GLOBALS['siteConf']['template_vars_mode']:

Note:

Usage Scenarios

Scenario 1: Procedural usage (file top level)

<?php
// index.php - file top level
require_once 'Template.php';

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

// Option 1: use global variables (backward compatible)
$GLOBALS['user'] = $user;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);

// Option 2: pass explicitly (recommended, safer)
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, ['user' => $user]);

Scenario 2: Usage inside a function

<?php
// functions.php
function renderUserProfile($userId) {
    $tplDir = '/path/to/templates/';
    $cacheDir = '/path/to/cache/';
    
    // Fetch data (local variables)
    $user = getUserById($userId);
    $posts = getUserPosts($userId);
    $stats = getUserStats($userId);
    
    // Recommended: pass explicitly (avoids polluting global variables)
    return Zandy_Template::outString('user_profile.htm', $tplDir, $cacheDir, false, [
        'user' => $user,
        'posts' => $posts,
        'stats' => $stats
    ]);
}

Scenario 3: Usage inside a class method

<?php
// Controller.php
class UserController {
    private $tplDir = '/path/to/templates/';
    private $cacheDir = '/path/to/cache/';
    
    public function showProfile($userId) {
        // Fetch data (local variables)
        $user = $this->getUserById($userId);
        $posts = $this->getUserPosts($userId);
        
        // Recommended: pass explicitly
        return Zandy_Template::outString('user_profile.htm', $this->tplDir, $this->cacheDir, false, [
            'user' => $user,
            'posts' => $posts
        ]);
    }
    
    public function renderProfile($userId) {
        // Use includeTemplate() (suited to direct output)
        $user = $this->getUserById($userId);
        $posts = $this->getUserPosts($userId);
        
        Zandy_Template::includeTemplate('user_profile.htm', $this->tplDir, $this->cacheDir, false, [
            'user' => $user,
            'posts' => $posts
        ]);
    }
}

Scenario 4: Using outCache() + include

<?php
// Procedural usage
$GLOBALS['user'] = $user;
$cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
extract(Zandy_Template::getTemplateVars());  // uses the configured mode
include $cacheFile;

// Usage inside a function (recommended)
function renderPage() {
    $user = getUser();
    
    // Option 1: use includeTemplate() (most recommended)
    Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir, false, [
        'user' => $user
    ]);
    
    // Option 2: use the getTemplateVars() helper
    $cacheFile = Zandy_Template::outCache('template.htm', $tplDir, $cacheDir);
    extract(Zandy_Template::getTemplateVars(['user' => $user]));
    include $cacheFile;
}

Scenario 5: Using template test (Tests) syntax

<!-- user_list.htm -->
<!--{if $users is array and is not empty}-->
    <ul>
        <!--{loop $users as $user}-->
            <li>
                <!--{if $user is not null}-->
                    <strong>{$user['name']}</strong>
                    <!--{if $user['email'] is not empty}-->
                        <span>{$user['email']}</span>
                    <!--{/if}-->
                <!--{else}-->
                    <em>User does not exist</em>
                <!--{/if}-->
            </li>
        <!--{/loop}-->
    </ul>
<!--{elseif $users is null}-->
    <p>Failed to load data</p>
<!--{else}-->
    <p>No users yet</p>
<!--{/if}-->

Explanation:

Scenario 6: Using macro definitions (Macros)

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

<!-- Define a macro: show a user information card -->
<!--{macro name="userCard" user="" showEmail="true"}-->
    <div class="user-card">
        <h3>{$user['name']}</h3>
        <!--{if $showEmail == "true"}-->
            <p>{$user['email']}</p>
        <!--{/if}-->
    </div>
<!--{/macro}-->

<!-- Call a macro: using string arguments -->
<p>Publish date: <!--{call name="formatDate" date="2026-01-15" format="Y-m-d H:i:s"}--></p>

<!-- Call a macro: using variable arguments -->
<p>Publish date: <!--{call name="formatDate" date="$postDate" format="Y-m-d"}--></p>

<!-- Call a macro: multiple arguments -->
<!--{call name="userCard" user="$currentUser" showEmail="false"}-->

<!-- Use a macro inside a loop -->
<!--{loop $users as $user}-->
    <!--{call name="userCard" user="$user" showEmail="true"}-->
<!--{/loop}-->

The plugin must be loaded before use:

require_once 'plugins/macros.php';

Explanation:

Best Practices

1. Variable Passing

Recommended:

Not recommended:

1.1 Plugin Loading Notes

1.2 Debugging and PHP Capability Syntax

2. outCache Scenarios

Recommended:

Not recommended:

3. Template Test (Tests) Syntax

Recommended:

Example:

<!-- ✅ Recommended: use template test syntax -->
<!--{if $items is array and is not empty}-->
    <!-- process the array -->
<!--{/if}-->

<!-- ❌ Not recommended: mixed style (unsupported) -->
<!--{if $items is array && !empty($items)}-->
    <!-- this style causes a syntax error -->
<!--{/if}-->

Not recommended:

4. Macro Definitions (Macros)

Recommended:

Example:

<!-- ✅ Recommended: define a reusable macro -->
<!--{macro name="userCard" user="" showEmail="true"}-->
    <div class="user-card">
        <h3>{$user['name']}</h3>
        <!--{if $showEmail == "true"}-->
            <p>{$user['email']}</p>
        <!--{/if}-->
    </div>
<!--{/macro}-->

<!-- Use the macro inside a loop -->
<!--{loop $users as $user}-->
    <!--{call name="userCard" user="$user"}-->
<!--{/loop}-->

Not recommended:

4. Security Configuration

Development environment:

// The fully open mode (default) may be used for convenient debugging
// No extra configuration needed

Production environment:

// Whitelist mode is recommended
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data', 'items'];

High security requirements:

// Use explicit passing mode
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
    'user' => $user,
    'data' => $data
]);

4. HTML Escaping and XSS Protection

Escaping strategy:

Usage scenarios:

  1. User input (must be escaped):

    <!-- ✅ Correct: escape user input to prevent XSS attacks -->
    Username: {$username|escape}
    Comment: {$comment|escape}
    Search keyword: {$keyword|escape}
  2. System content (may be left unescaped):

    <!-- ✅ Acceptable: system-generated content -->
    Title: {$title}
    Description: {$description}
  3. Filter chains:

    <!-- Multiple filters can be combined -->
    {$username|upper|escape}              <!-- uppercase first, then escape -->
    {$description|truncate:50|escape}    <!-- truncate first, then escape -->

Security tips:

5. Untrusted Template Source

If the template source is untrusted, you must:

  1. Use explicit passing mode
  2. Disable PHP code blocks (where possible)
  3. Strictly validate template paths
  4. All user input must be escaped (using |escape)

More Information