2022-10-28 17:00:16 +02:00

55 lines
1.3 KiB
PHP

<?php
/*
* Copyright (c) 2022 Micha Espey <tracer@24unix.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Service;
/*
* As I'm not allowed to use 3rd party code like Twig or Smarty I ended up
* using PHP as a templating engine.
*/
class Template
{
/*
* Just store the information about the template base dir.
*/
public function __construct(private readonly string $templateDir)
{
// empty body
}
/*
* Add variables to template and throw it out
*/
public function render(string $templateName, array $vars = []): never
{
// assign template vars
foreach ($vars as $name => $value) {
$$name = $value;
}
$templateFile = $this->templateDir . $templateName;
if (file_exists(filename: $templateFile)) {
include $this->templateDir . $templateName;
} else {
die("Missing template: $templateFile");
}
exit(0);
}
/*
* For AJAX calls, return json
*/
public function renderJson(array $results): never
{
http_response_code(response_code: $results['status']);
echo json_encode(value: $results);
exit(0);
}
}