web-base/core/Elements/TemplateDocument.class.php

79 lines
2.3 KiB
PHP
Raw Normal View History

2021-12-08 16:53:43 +01:00
<?php
namespace Elements;
2022-06-01 12:28:50 +02:00
use Objects\Router\Router;
2021-12-08 16:53:43 +01:00
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Loader\FilesystemLoader;
class TemplateDocument extends Document {
private string $templateName;
protected array $parameters;
private Environment $twigEnvironment;
private FilesystemLoader $twigLoader;
2022-02-20 16:53:26 +01:00
protected string $title;
2021-12-08 16:53:43 +01:00
2022-06-01 12:28:50 +02:00
public function __construct(Router $router, string $templateName, array $params = []) {
parent::__construct($router);
2022-02-20 16:53:26 +01:00
$this->title = "";
2021-12-08 16:53:43 +01:00
$this->templateName = $templateName;
2022-05-31 16:14:49 +02:00
$this->parameters = $params;
2021-12-08 16:53:43 +01:00
$this->twigLoader = new FilesystemLoader(WEBROOT . '/core/Templates');
$this->twigEnvironment = new Environment($this->twigLoader, [
2022-05-31 16:14:49 +02:00
'cache' => WEBROOT . '/core/Cache/Templates/',
2021-12-08 16:53:43 +01:00
'auto_reload' => true
]);
}
protected function getTemplateName(): string {
return $this->templateName;
}
protected function loadParameters() {
}
2022-05-31 16:14:49 +02:00
public function getCode(array $params = []): string {
parent::getCode($params);
2021-12-08 16:53:43 +01:00
$this->loadParameters();
return $this->renderTemplate($this->templateName, $this->parameters);
}
public function renderTemplate(string $name, array $params = []): string {
try {
2022-06-01 12:28:50 +02:00
$user = $this->getUser();
2021-12-08 16:53:43 +01:00
$params["user"] = [
2022-06-01 12:28:50 +02:00
"lang" => $user->getLanguage()->getShortCode(),
"loggedIn" => $user->isLoggedIn(),
"session" => (!$user->isLoggedIn() ? null : [
"csrfToken" => $user->getSession()->getCsrfToken()
2022-02-20 16:53:26 +01:00
])
2021-12-08 16:53:43 +01:00
];
2022-06-01 12:28:50 +02:00
$settings = $this->getSettings();
2021-12-08 16:53:43 +01:00
$params["site"] = [
"name" => $settings->getSiteName(),
"baseUrl" => $settings->getBaseUrl(),
2022-02-21 14:04:49 +01:00
"registrationEnabled" => $settings->isRegistrationAllowed(),
2022-02-20 16:53:26 +01:00
"title" => $this->title,
2021-12-08 16:53:43 +01:00
"recaptcha" => [
"key" => $settings->isRecaptchaEnabled() ? $settings->getRecaptchaSiteKey() : null,
"enabled" => $settings->isRecaptchaEnabled(),
],
"csp" => [
"nonce" => $this->getCSPNonce(),
"enabled" => $this->isCSPEnabled()
]
];
return $this->twigEnvironment->render($name, $params);
} catch (LoaderError | RuntimeError | SyntaxError $e) {
return "<b>Error rendering twig template: " . htmlspecialchars($e->getMessage()) . "</b>";
}
}
}