PHP Template Engines
In this page:
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
$template = "Hello, {{ name }}!";
$data = ["name" => "Alice"];
echo str_replace("{{ name }}", $data["name"], $template);
?>
Login to try C/C++/Java/PHP code in the editor
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
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]);
?>
Login to try C/C++/Java/PHP code in the editor
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
function renderLayout($content) {
return "<html><body>$content</body></html>";
}
$pageContent = "<h1>Home Page</h1>";
echo renderLayout($pageContent);
?>
Login to try C/C++/Java/PHP code in the editor
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
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>"]);
?>
Login to try C/C++/Java/PHP code in the editor
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
function header() { return "<header>Site Header</header>"; }
function footer() { return "<footer>Site Footer</footer>"; }
echo header() . "<main>Page content</main>" . footer();
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: