# Templates A simple template engine separates logic from the presentation and provides methods for creating nested templates and escaping strings to protect against too common XSS vulnerabilities. Template engine initialization: ```php $template = new App\Template\Engine(__DIR__.'/../path/to/templates'); ``` Site-wide configuration parameters can be assigned before rendering so they are available in all templates: ```php $template->assign([ 'siteUrl' => 'https://bugs.php.net', // ... ]); ``` Page can be rendered in the controller: ```php echo $template->render('pages/how_to_report.php', [ 'mainHeading' => 'How to report a bug?', ]); ``` The `templates/pages/how_to_report.php`: ```php extends('layout.php', ['title' => 'Reporting bugs']) ?> start('main_content') ?>

noHtml($mainHeading) ?>

end('main_content') ?> start('scripts') ?> end('scripts') ?> ``` The `templates/layout.php`: ```html PHP Bug Tracking System :: <?= $title ?? '' ?> block('main_content') ?>
block('scripts') ?> ``` ## Including templates To include a partial template snippet file: ```php include('forms/report_bug.php') ?> ``` which is equivalent to ``, except that the variable scope is not inherited by the template that included the file. To import variables into the included template snippet file: ```php include('forms/contact.php', ['formHeading' => 'value', 'foo' => 'bar']) ?> ``` ## Blocks Blocks are main building elements that contain template snippets and can be included into the parent file(s). Block is started with the `$this->start('block_name')` call and ends with `$this->end('block_name')`: ```php start('block_name') ?>

Heading

...

end('block_name') ?> ``` ### Appending blocks Block content can be appended to existing blocks by the `$this->append('block_name')`. The `templates/layout.php`: ```html block('content'); ?> block('scripts'); ?> ``` The `templates/pages/index.php`: ```php extends('layout.php'); ?> start('scripts'); ?> end('scripts'); ?> start('content') ?> include('forms/form.php') ?> end('content') ?> ``` The `templates/forms/form.php`: ```php
append('scripts'); ?> end('scripts'); ?> ``` The final rendered page: ```html
``` ## Helpers Registering additional template helpers can be useful when a custom function or class method needs to be called in the template. ### Registering function ```php $template->register('formatDate', function (int $timestamp): string { return gmdate('Y-m-d H:i e', $timestamp - date('Z', $timestamp)); }); ``` ### Registering object method ```php $template->register('doSomething', [$object, 'methodName']); ``` Using helpers in templates: ```php

Time: formatDate(time()) ?>

doSomething('arguments') ?>
``` ## Escaping When protecting against XSS there are two built-in methods provided. To replace all characters to their applicable HTML entities in the given string: ```php noHtml($var) ?> ``` To escape given string and still preserve certain characters as HTML: ```php e($var) ?> ```