🦖
[] API тайлбар
codesaur/template GitHub дээр үзэх

API Documentation - codesaur/template

Last Updated: 2026-03-30


Table of Contents


Overview

codesaur/template нь 2 үндсэн класс-аас бүрдэнэ:

  1. MemoryTemplate - Бүрэн template engine (if, for, filter, function, macro, expression parser, 33 built-in filter)
  2. FileTemplate - Файлын системээс template уншиж рэндэрлэх wrapper (MemoryTemplate-ийг өргөтгөнө)

Inheritance Hierarchy:

MemoryTemplate  (бүрэн engine)
    |-- FileTemplate  (файл уншигч wrapper)

MemoryTemplate

Бүрэн template engine. If, for, macro, filter, function, expression parser бүгдийг агуулна.

Class Signature

class MemoryTemplate

Properties

protected string $html

Темплейтийн үндсэн HTML эсвэл текст эх.

protected array<string, mixed> $vars

Темплейтэд оруулах хувьсагчдын массив.

protected array<string, callable> $filters

Бүртгэгдсэн filter-үүд.

protected array<string, callable> $functions

Бүртгэгдсэн function-үүд.


Constructor

__construct(string $template = '', array $vars = [])

MemoryTemplate объект үүсгэх. Built-in filter, function-уудыг автоматаар бүртгэнэ.

Parameters:

  • string $template - Темплейтийн эхлэл утга (default: '')
  • array $vars - Хувьсагчдын массив (default: [])

Example:

$template = new MemoryTemplate('Hello, {{ name }}!', ['name' => 'World']);

Хувьсагч удирдлага (Variable Management)

set(string $key, $value): void

Хувьсагч нэмэх эсвэл шинэчлэх.

$template->set('name', 'John');

setVars(array $values): void

Олон хувьсагч нэгэн зэрэг нэмэх.

$template->setVars(['name' => 'John', 'age' => 30]);

get(string $key): mixed

Хувьсагчийн утгыг reference байдлаар буцаана. Олдохгүй бол null.

$value = &$template->get('name');

getVars(): array<string, mixed>

Бүх хувьсагчдын массивыг буцаана.

$vars = $template->getVars();

Template source удирдлага

source(string $html): void

Темплейтийн эх агуулгыг тохируулна.

$template->source('<h1>{{ title }}</h1>');

getSource(): string

Темплейтийн эх агуулгыг буцаана.

$source = $template->getSource();

Output

output(): string

Темплейтийг compile хийж финал HTML буцаана.

$html = $template->output();

render(): void

Темплейтийг compile хийж echo хийнэ.

$template->render();

__toString(): string

Объектыг echo хийх үед output() дуудагдана.

echo $template;

Filter / Function бүртгэх

addFilter(string $name, callable $callback): void

Custom filter нэмэх. Template дотор {{ value|name }} хэлбэрээр ашиглана.

$template->addFilter('truncate', fn($v, int $len = 100) => mb_substr((string) $v, 0, $len));
// {{ description|truncate(50) }}

addFunction(string $name, callable $callback): void

Custom function нэмэх. Template дотор {{ name(args) }} хэлбэрээр ашиглана.

$template->addFunction('link', fn($route) => "/app/$route");
// {{ link('home') }}

FileTemplate

MemoryTemplate-ийг өргөтгөж, файлын системээс template уншиж рэндэрлэнэ. Бүх engine логик нь MemoryTemplate-д байдаг. FileTemplate зөвхөн файл уншиж дамжуулна.

Class Signature

class FileTemplate extends MemoryTemplate

Properties

protected string $filepath

Темплейт файлын бүрэн зам.


Methods

__construct(string $template = '', array $vars = [])

FileTemplate конструктор.

Parameters:

  • string $template - Темплейт файлын зам (хоосон байж болно)
  • array $vars - Хувьсагчдын массив (default: [])
$template = new FileTemplate(__DIR__ . '/template.html', ['name' => 'World']);

file(string $filepath): void

Темплейт файлын замыг тохируулна.

Throws: \InvalidArgumentException - Файлын нэр хоосон байвал

$template->file(__DIR__ . '/template.html');

getFileName(): string

Темплейт файлын замыг буцаана.

$path = $template->getFileName();

getFileSource(): string

Файлын агуулгыг уншиж буцаана.

Throws: \RuntimeException - Файл олдохгүй эсвэл уншихад алдаа гарвал

$content = $template->getFileSource();

output(): string

Файлыг уншиж compile хийж финал HTML буцаана.

Throws: \RuntimeException - Файл уншихад алдаа гарвал

$html = $template->output();

Inherited Methods

FileTemplate нь MemoryTemplate-ийн бүх public method-уудыг өвлөж авна:

  • Хувьсагч удирдлага: set, setVars, get, getVars
  • Template source: source, getSource
  • Output: render, __toString
  • Filter/Function: addFilter, addFunction

Built-in Filters

MemoryTemplate конструктор дотор автоматаар бүртгэгддэг filter-үүд:

FilterТайлбарЖишээ
intТоон хөрвүүлэг{{ value|int }}
roundТоймлох{{ price|round(2) }}
number_formatТоон формат{{ price|number_format(2, '.', ',') }}
json_encodeJSON болгох{{ data|json_encode }}
upperТом үсэг{{ name|upper }}
lowerЖижиг үсэг{{ name|lower }}
capitalizeЭхний үсэг том{{ name|capitalize }}
nl2brМөр таслал -> <br>{{ text|nl2br }}
url_encodeURL encode{{ url|url_encode }}
rawEscape хийхгүй{{ html|raw }}
e / escapeHTML escape{{ input|e }}
dateОгноо формат{{ d|date('Y-m-d') }}
lengthУрт{{ items|length }}
keysМассивын түлхүүрүүд{{ data|keys }}
firstЭхний элемент{{ items|first }}
lastСүүлийн элемент{{ items|last }}
sliceХэсэг авах{{ text|slice(0, 5) }}
mergeМассив нэгтгэх{{ arr|merge([4, 5]) }}
splitТэмдэгтээр хуваах{{ csv|split(',') }}
defaultӨгөгдмөл утга{{ name|default('Unknown') }}
formatsprintf{{ 'Hi %s'|format(name) }}
absАбсолют утга{{ num|abs }}
trimХоосон зай арилгах{{ text|trim }}
striptagsHTML tag арилгах{{ html|striptags }}
titleTitle Case{{ name|title }}
joinМассив нэгтгэх{{ items|join(', ') }}
reverseЭргүүлэх{{ items|reverse }}
sortЭрэмбэлэх{{ items|sort }}
uniqueДавхардал арилгах{{ items|unique }}
columnМассивын нэг багана{{ users|column('name') }}
batchХэсэгчлэх{{ items|batch(3) }}
valuesЗөвхөн утгууд{{ data|values }}
replaceТекст солих{{ text|replace({'a': 'b'}) }}
wordwrapМөр таслах{{ text|wordwrap(80) }}
json_decodeJSON задлах{{ json|json_decode }}

Built-in Functions

FunctionТайлбарЖишээ
attributeМассивын элемент авах{{ attribute(obj, key) }}
rangeТоон цуваа{{ range(1, 10) }}
maxХамгийн их{{ max(a, b) }}
minХамгийн бага{{ min(a, b) }}

Supported Template Syntax

Output

  • {{ variable }} - Хувьсагч
  • {{ variable|filter }} - Filter chain
  • {{ function(args) }} - Function дуудалт
  • {{ a ? b : c }} - Ternary operator
  • {{ a ?? b }} - Null coalescing
  • {{ a ~ b }} - Concat operator

Control Structures

  • {% if cond %}...{% elseif cond %}...{% else %}...{% endif %}
  • {% for item in items %}...{% endfor %}
  • {% for item in items %}...{% else %}...{% endfor %} (items хоосон / iterable биш үед else хэсгийг render хийнэ)
  • {% for key, val in items %}...{% endfor %}
  • {% set name = value %}
  • {% macro name(params) %}...{% endmacro %}

Loop Variables

{% for %} дотор loop объект ашиглах боломжтой:

  • loop.index (1-ээс эхэлнэ)
  • loop.index0 (0-ээс эхэлнэ)
  • loop.first (эхний давталт уу?)
  • loop.last (сүүлийн давталт уу?)
  • loop.length (нийт тоо)

Tests

  • is defined, is empty, is null, is iterable, is even, is odd
  • is not defined, is not empty гэх мэт

Operators

  • Харьцуулах: ==, !=, <, >, <=, >=
  • Логик: and, or, not
  • Гишүүнчлэл: in, not in - {% if type in ['image', 'video'] %} (массив, тэмдэгт мөр, Traversable)
  • Тэмдэгт: starts with, ends with, matches (regex) - {% if email matches '/^[^@]+@[^@]+$/' %}
  • Тооцоолол: +, -, *, /, % болон unary minus (-5, -price)

Literals

  • String: 'hello', "hello"
  • Number: 42, 3.14
  • Boolean: true, false
  • Null: null, none
  • Array: [1, 2, 3]
  • Hash: {'key': 'value'}

Access

  • Dot notation: user.name
  • Bracket notation: user['name']
  • Filter chain: value|filter1|filter2(arg)
  • Method дуудлага: user.can('edit'), auth.is('admin') (method_exists шалгалттайгаар object-ийн public method дуудна)
  • Callable map дуудлага: helpers.upper('hi') (массивын callable элементийг шууд дуудна)

Examples

MemoryTemplate -- бүрэн engine

use codesaur\Template\MemoryTemplate;

$t = new MemoryTemplate(
    '{% for item in items %}{{ loop.index }}. {{ item|upper }} {% endfor %}',
    ['items' => ['php', 'js', 'go']]
);
echo $t; // 1. PHP 2. JS 3. GO

// Custom function
$t = new MemoryTemplate('{{ greet("World") }}');
$t->addFunction('greet', fn($name) => "Hello, $name!");
echo $t; // Hello, World!

// Custom filter
$t = new MemoryTemplate('{{ name|reverse }}', ['name' => 'hello']);
$t->addFilter('reverse', fn($v) => strrev((string) $v));
echo $t; // olleh

// for/else - items хоосон үед else хэсэг render хийгдэнэ
$t = new MemoryTemplate(
    '{% for item in items %}{{ item }},{% else %}empty{% endfor %}',
    ['items' => []]
);
echo $t; // empty

// Илэрхийлэлд object-ийн method дуудах
$user = new class {
    public function can(string $perm): bool { return $perm === 'edit'; }
};
$t = new MemoryTemplate(
    "{{ user.can('edit') ? 'yes' : 'no' }}|{{ user.can('admin') ? 'yes' : 'no' }}",
    ['user' => $user]
);
echo $t; // yes|no

FileTemplate

use codesaur\Template\FileTemplate;

$template = new FileTemplate(__DIR__ . '/page.html', [
    'title' => 'My Page',
    'users' => [['name' => 'John'], ['name' => 'Jane']]
]);
$template->addFunction('link', fn($route, $params = []) => '/app/' . $route);
echo $template->output();

Exception Reference

\InvalidArgumentException

  • FileTemplate::file() - Файлын нэр хоосон байвал

\RuntimeException

  • FileTemplate::getFileSource() - Файл олдохгүй эсвэл уншихад алдаа гарвал
  • FileTemplate::output() - Файл уншихад алдаа гарвал

Best Practices

  1. MemoryTemplate - бүрэн engine тул ихэнх тохиолдолд хангалттай
  2. FileTemplate - зөвхөн файлын системээс template уншихад ашиглана
  3. Custom function - text(), link() гэх мэт утга үүсгэгч логикийг function-ээр бүртгэ
  4. Custom filter - |reverse, |truncate гэх мэт утга хувиргагчийг filter-ээр бүртгэ
  5. HTML comments - Template дотор <!-- comment --> ашиглана ({# #} дэмжигдэхгүй)