Template Engine from Scratch

Separating logic from presentation makes your code easier to maintain. While many frameworks include templating engines, building a simple one yourself demystifies the process and gives you control.

Using output buffering

PHP’s output buffering functions capture echoed output into a string. You can include a PHP view file and fetch its contents:

<?php declare(strict_types=1); function render(string $template, array $data = []): string { extract($data, EXTR_SKIP); ob_start(); include $template; return ob_get_clean(); } ?>

Create a view file like views/greeting.php that uses variables passed via $data:

<h1>Hello, <?= htmlspecialchars($name) ?>!</h1>

You can now call render('views/greeting.php', ['name' => 'Alice']) to produce safe, escaped output.

Replacing placeholders

A more basic approach uses str_replace() on a template string. Load the template file, replace placeholders with values and return the result:

<?php declare(strict_types=1); function simpleTemplate(string $file, array $vars): string { $template = file_get_contents($file); foreach ($vars as $key => $value) { $template = str_replace('{{' . $key . '}}', htmlspecialchars((string)$value), $template); } return $template; } ?>

This simple engine cannot handle loops or conditionals, but illustrates the core idea behind templating.