← Back to PHP Course | Chapter 15: Web Development | Lesson 2 of 12

PHP Template Engines

What is a Template Engine?

A template engine keeps presentation markup separate from application logic, letting designers edit templates using simple placeholders without needing to understand the PHP that populates them.

Example: What is a Template Engine?

php
<?php
$template = "Hello, {{ name }}!";
$data = ["name" => "Alice"];
echo str_replace("{{ name }}", $data["name"], $template);
?>

Basic Variable Parsing

At its core, a template engine scans a template string for placeholders (like {{ name }}) and substitutes the corresponding variable's value, which is what keeps view files free of dense PHP control structures.

Example: Basic Variable Parsing

php
<?php
function render($template, $data) {
    foreach ($data as $key => $value) {
        $template = str_replace("{{ $key }}", $value, $template);
    }
    return $template;
}
echo render("Hi {{ name }}, you are {{ age }}", ["name" => "Alice", "age" => 30]);
?>

Simulating Layout Inheritance

Layout inheritance lets a child template declare that it extends a shared parent layout and only override specific named blocks (like a page title or main content area), avoiding repeated header/footer markup in every view.

Example: Simulating Layout Inheritance

php
<?php
function renderLayout($content) {
    return "<html><body>$content</body></html>";
}
$pageContent = "<h1>Home Page</h1>";
echo renderLayout($pageContent);
?>

Safe Output Escaping

Because raw user data can contain malicious HTML or scripts, template engines escape variable output by default before printing it, closing off a major XSS attack surface automatically.

Example: Safe Output Escaping

php
<?php
function render($template, $data) {
    foreach ($data as $key => $value) {
        $template = str_replace("{{ $key }}", htmlspecialchars($value), $template);
    }
    return $template;
}
echo render("Comment: {{ text }}", ["text" => "<script>alert(1)</script>"]);
?>

Modular Views

Splitting a layout into smaller included files -- a header, a footer, a nav bar -- keeps each piece focused and reusable across many pages, even without a full templating library.

Example: Modular Views

php
<?php
function header() { return "<header>Site Header</header>"; }
function footer() { return "<footer>Site Footer</footer>"; }
echo header() . "<main>Page content</main>" . footer();
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.