# 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') ?>
= $siteUrl ?>
end('main_content') ?> start('scripts') ?> end('scripts') ?> ``` The `templates/layout.php`: ```html...
end('block_name') ?> ``` ### Appending blocks Block content can be appended to existing blocks by the `$this->append('block_name')`. The `templates/layout.php`: ```html = $this->block('content'); ?> = $this->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: ```phpTime: = $this->formatDate(time()) ?>