Kotchasan Framework Documentation

Kotchasan Framework Documentation

Template

EN 05 Feb 2026 06:23

Template

Kotchasan\Template is a class for managing HTML Templates, supporting variable replacement and loading templates from themes.

Basic Usage

Creating Template from HTML

use Kotchasan\Template;

// Create Template from HTML String
$html = '<div class="alert">{CONTENT}</div>';
$template = Template::createFromHTML($html);

// Replace {CONTENT} variable
// Note: Key MUST be a Regex Pattern
$template->add(['/{CONTENT}/' => 'Hello World']);

// Render output
echo $template->render();
// Output: <div class="alert">Hello World</div>

Loading Template from File

// Load my_template.html from 'user' module
$template = Template::load('user', '', 'my_template');

Methods

createFromHTML(string $html): static

Creates a Template instance from an HTML string.

  • $html: Raw HTML code.
  • Returns: Template instance.

createFromFile(string $filename): static

Creates a Template instance from a file path.

  • $filename: Absolute path to file.

add(array $array): static

Replaces variables in the template with specified values.

  • $array: Array of Keys (Regex Patterns) and Values.

[!IMPORTANT]
The Array Keys MUST be Regex Patterns (e.g., /{NAME}/ or /^NAME$/). Plain strings will not work.

$template->add([
    '/{TITLE}/' => $title,
    '/{CONTENT}/' => $content
]);

render(): string

Returns the processed HTML.

  • Returns: HTML String.

insertHTML(string $html): static

Appends HTML content directly to the item list.

init(string $theme)

Sets the active Theme folder (used by load()).

  • $theme: Theme folder name (e.g., 'default').

Grid Usage

Template supports Grid layout (Row/Col) via protected properties (typically used via the Grid subclass).

Practical Example

$view = new Template;
$view->init('default'); // Use 'default' theme

// Load main.html from Theme
$template = Template::create('Gcms', 'index', 'main');

// Replace content
$template->add([
    '/{WEB_TITLE}/' => 'My Website',
    '/{CONTENT}/' => 'Welcome to my site'
]);

echo $template->render();